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


when have string contains space characters:

var str = '  b  c   d ef '; 

and want remove spaces string (we want this: 'abcdef').

both this:

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

and this:

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

will return correct result.

does mean + superfluous in situation? there difference between 2 regular expressions in situation (as in, in way produce different results)?


update: performance comparison - /\s+/g faster. see here: http://jsperf.com/s-vs-s

in first regex, each space character being replaced, character character, empty string.

in second regex, each contiguous string of space characters being replaced empty string because of +.

however, how 0 multiplied else 0, seems if both methods strip spaces in same way.

if change replacement string '#', difference becomes clearer:

var str = '  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# 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -