Why does strip not remove the leading whitespace? Why does strip not remove the leading whitespace? ruby ruby

Why does strip not remove the leading whitespace?


Where did the string " Bagsværd" come from?

It’s likely that the space character at the start of the string is not a “normal” space, but a non-breaking space (U+00A0):

2.0.0p353 :001 > " Bagsværd".strip => "Bagsværd" 2.0.0p353 :002 > "\u00a0Bagsværd".strip => " Bagsværd" 

You could remove it with gsub rather than strip:

2.0.0p353 :003 > "\u00a0Bagsværd".gsub(/\A\p{Space}*/, '') => "Bagsværd" 

This uses the \A anchor, and the \p{Space} character property to emulate lstrip. To strip both leading and trailing whitespace, use:

2.0.0p353 :007 > "\u00a0Bagsværd\u00a0".gsub(/\A\p{Space}*|\p{Space}*\z/, '') => "Bagsværd" 


The first character in your string is not whitespace

" Bagsværd".bytes[194, 160, 66, 97, 103, 115, 118, 195, 166, 114, 100]" Bagsværd".chars[0].ord => 160

This is U+00A0 no-break space. Note I could tell this because the editable form of the question preserves the character (whilst anyone trying to cut and paste from the rendered SO post would not be able to replicate your problem)


The most likely way that strip isn't removing a space, is when it isn't really a space, but is a non-breaking space.

Try this on your machine:

# encoding: utf-8" Bagsværd".chars.map(&:ord)

On mine, using Ruby 2.0.0p353:

# => [160, 66, 97, 103, 115, 118, 230, 114, 100]