TheExit
TheExit

Reputation: 5320

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?

Upvotes: 117

Views: 80222

Answers (5)

piton4eg
piton4eg

Reputation: 1106

Maybe this will work for such case:

# do not replace any word characters and spaces
@search_query = @search_query.gsub(/[^\w ]/g, '')

Upvotes: 0

Vadym Tyemirov
Vadym Tyemirov

Reputation: 8833

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

Upvotes: 3

nvugteveen
nvugteveen

Reputation: 516

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.

Upvotes: 16

John Doe
John Doe

Reputation: 219

A better answer (at least in ruby) is:

@search_query.gsub!(/^(\w|\s*)/,'')

Upvotes: -3

jwueller
jwueller

Reputation: 30996

Add spaces to the negated character group:

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

Upvotes: 208

Related Questions