How do I strip non alphanumeric characters from a string and keep spaces?

Solution 1:

Add spaces to the negated character group:

@search_query = @search_query.gsub(/[^0-9a-z ]/i, '')

Solution 2:

In this case I would use the bang method (gsub! instead of gsub) in order to clean the input permanently.

#permanently filter all non-alphanumeric characters, except _
@search_query.gsub!(/\W/,'')

This avoids a situation where @seach_query is used elsewhere in the code without cleaning it.