ruby-on-railsrubyregexruby-on-rails-3

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


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?


Solution

  • Add spaces to the negated character group:

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