Industrial
Industrial

Reputation: 42758

Why does my regexp not work when the strings end with spaces?

I am using this regexp - [^\s\da-zA-ZåäöÅÄÖ]+$ to filter out anything but A-Z, 0-9 plus the Swedish characters ÅÄÖ. It works as expected as long as the string isn't ending with whitespace and I am a bit confused on what I need correct to make it accept strings even if they end with whitespace. The \s is there but is apparently not enough.

What is wrong in my regexp?

"something #¤%&/()=?".replace(/[^\s\da-zA-ZåäöÅÄÖ]+$/, '') # => a string


"something ending with whitespace #¤%&/()=? ".replace(/[^\s\da-zA-ZåäöÅÄÖ]+$/, '')# => a string ending with space #¤%&/()=? 

Upvotes: 2

Views: 160

Answers (2)

Avish
Avish

Reputation: 4626

Your regex says: "match one or more instances of the characters not in the following range, followed by end-of-string". This essentially means that your regex will match only sequences of not-allowed characters appearing at the end of the string. Since your test string ends with a whitespace, which is allowed by your logic, there's no 'sequence of not-allowed characters appearing at the end of the string' and so the regex doesn't match anything.

You can achieve your desired filtering if you remove the $ from the end of the regex and instead use the g flag to make it globally replace anything not in the specified character range with the empty string.

If you additionally want to trim trailing whitespace, it'd be better to do so using another regex, or a simpler trimRight call.

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

You're using a negated character class ("anything that is not a space, a digit, a letter etc."), therefore your regex fails to match.

Drop the \s from it, and also the $ (which ties the match to the end of the string), and it should work.

If you do want to keep spaces inside the string and only remove them at the end, use

"something with whitespace #¤%&/()=? ".replace(/[^\s\da-zA-ZåäöÅÄÖ]+|\s+$/g, '')

Result:

something with whitespace

Upvotes: 2

Related Questions