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
\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. Follow this answer to receive notifications.
The RegExp \s Metacharacter in JavaScript is used to find the whitespace characters. The whitespace character can be a space/tab/new line/vertical character. It is same as [ \t\n\r]. Syntax: /\s/
i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.
2.7 Backslash (\) and Regex Escape Sequences Regex uses backslash ( \ ) for two purposes: for metacharacters such as \d (digit), \D (non-digit), \s (space), \S (non-space), \w (word), \W (non-word). to escape special regex characters, e.g., \. for . , \+ for + , \* for * , \? for ? .
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#
\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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With