How do I strip non alphanumeric characters from a string and keep spaces?
Ruby on-RailsRubyRegexRuby on-Rails-3Ruby on-Rails Problem Overview
I want to create a regex that removes all non-alphanumber characters but keeps spaces. This is to clean search input before it hits the db. Here's what I have so far:
@search_query = @search_query.gsub(/[^0-9a-z]/i, '')
Problem here is it removes all the spaces. Solutions on how to retain spaces?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
Add spaces to the negated character group:
@search_query = @search_query.gsub(/[^0-9a-z ]/i, '')
Solution 2 - Ruby on-Rails
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.
Solution 3 - Ruby on-Rails
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
Solution 4 - Ruby on-Rails
Maybe this will work for such case:
# do not replace any word characters and spaces
@search_query = @search_query.gsub(/[^\w ]/g, '')
Solution 5 - Ruby on-Rails
A better answer (at least in ruby) is:
@search_query.gsub!(/^(\w|\s*)/,'')