views:

146

answers:

2

I have someone entering a form with some string input. What I need to do is replace any white space in the string with " AND " (no quotes). What's the best way to do this?

Also, how would I go about doing this if I wanted to remove all the whitespace in the string?

Thanks

+5  A: 

to replace with and:

s = 'this has   some     whitespace'
s.gsub! /\s+/, ' AND '

=> "this AND has AND some AND whitespace"

to remove altogether:

s = 'this has   some     whitespace'
s.gsub! /\s+/, ''

=> "thishassomewhitespace"
Peter
How would you check to see if the string has white space already in it?
Splashlin
You can use `s =~ /\s/`.
Peter
+1  A: 

Split and join is another technique:

s = "   a   b   c   "
s.split(' ').join(' AND ')
# => "a AND b AND c"

This has the advantage of ignoring leading and trailing whitespace that Peter's RE does not:

s = "   a   b   c   "
s.gsub /\s+/, ' AND '
# => " AND a AND b AND c AND "

Removing whitespace

s.split(' ').join('')
# or
s.delete(' ')  # only deletes space chars
glenn jackman