Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  59] [ 2]  / answers: 1 / hits: 170797  / 13 Years ago, wed, may 11, 2011, 12:00:00

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


More From » regex

 Answers
49

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#

[#92289] Tuesday, May 10, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katelinb

Total Points: 535
Total Questions: 104
Total Answers: 109

Location: Burkina Faso
Member since Sun, Jun 13, 2021
3 Years ago
;