Regular Expression: Remove spaces from a string with JavaScript

When we have a string that contains space characters:

and we want to remove the spaces from the string (we want this: ‘ABCDEF’).

Both this:

and this:

will return the correct result.

\s means “one space”, and \s+ means “one or more spaces”.

In the first regex, each space character is being replaced, character by character, with the empty string.

In the second regex, each contiguous string of space characters is being replaced with the empty string because of the +.

However, just like how 0 multiplied by anything else is 0, it seems as if both methods strip spaces in exactly the same way.

If the replacement string is changed to ‘#’ instead of the empty string, the difference becomes much clearer:


Leave a Reply

Your email address will not be published. Required fields are marked *