开发者

Replace white space with AND in ruby

开发者 https://www.devze.com 2022-12-18 11:34 出处:网络
I have someone entering a form wi开发者_JAVA技巧th 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?

I have someone entering a form wi开发者_JAVA技巧th 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


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"


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


use gsub method for replacing whitespace

 s = "ajeet soni"

 => "ajeet soni" 

 s.gsub(" "," AND ")

 => "ajeet AND soni" 
0

精彩评论

暂无评论...
验证码 换一张
取 消