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

Add spaces to the negated character group:

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

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.


I would have used the inclusion approach. Rather than exclude all but numbers, I would only included numbers. E.g.

@search_query.scan(/[\da-z\s]/i).join