AnApprentice
AnApprentice

Reputation: 110960

Rails, how to replace all 2+ white spaces with &nbsp?

for my app if there is one white space that is fine. But if there is 2-4 I want to replace them with &nbsp to preserve the spacing.

What's the best way to do this with rails/regex? Or something else?

Desired Output:

' ' = ' '
'  ' = '  '
'   ' = '   '
'    ' = '    '

Upvotes: 3

Views: 3367

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219936

Why do you need both of them converted? Why not leave one as an actual space?

Then you could just use a lookahead:

srt.gsub(/ (?= )/, ' ')

See it here in action: http://regexr.com?2vodu

Upvotes: 6

mu is too short
mu is too short

Reputation: 434685

You just need a pattern that matches 2 or more spaces, then use the block form of gsub and look at how long the match is:

s.gsub(/ {2,}/) { ' ' * $&.length }

For example:

>> ' '.gsub(/ {2,}/) { ' ' * $&.length }
=> " "
>> (' ' * 2).gsub(/ {2,}/) { ' ' * $&.length }
=> "  "
>> (' ' * 3).gsub(/ {2,}/) { ' ' * $&.length }
=> "   "
>> (' ' * 11).gsub(/ {2,}/) { ' ' * $&.length }
=> "           "

Upvotes: 6

Related Questions