Is there a difference between /\s/g and /\s+/g?

JavascriptRegex

Javascript Problem Overview


When we have a string that contains space characters:

var str = '  A B  C   D EF ';

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

Both this:

str.replace(/\s/g, '')

and this:

str.replace(/\s+/g, '')

will return the correct result.

Does this mean that the + is superfluous in this situation? Is there a difference between those two regular expressions in this situation (as in, could they in any way produce different results)?


Update: Performance comparison - /\s+/g is faster. See here: http://jsperf.com/s-vs-s

Javascript Solutions


Solution 1 - Javascript

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 you change the replacement string to '#', the difference becomes much clearer:

var str = '  A B  C   D EF ';
console.log(str.replace(/\s/g, '#'));  // ##A#B##C###D#EF#
console.log(str.replace(/\s+/g, '#')); // #A#B#C#D#EF#

Solution 2 - Javascript

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

But, because you're using the /g flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect.

Solution 3 - Javascript

In a match situation the first would return one match per whitespace, when the second would return a match for each group of whitespaces.

The result is the same because you're replacing it with an empty string. If you replace it with 'x' for instance, the results would differ.

str.replace(/\s/g, 'x') will return 'xxAxBxxCxxxDxEF '

while str.replace(/\s+/g, 'x') will return 'xAxBxCxDxEF '

because \s matches each whitespace, replacing each one with 'x', and \s+ matches groups of whitespaces, replacing multiple sequential whitespaces with a single 'x'.

Solution 4 - Javascript

+ means "one or more characters" and without the plus it means "one character." In your case both result in the same output.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionŠime VidasView Question on Stackoverflow
Solution 1 - JavascriptBoltClockView Answer on Stackoverflow
Solution 2 - JavascriptLightness Races in OrbitView Answer on Stackoverflow
Solution 3 - JavascriptDougView Answer on Stackoverflow
Solution 4 - JavascriptJosh M.View Answer on Stackoverflow