简体   繁体   English

/\\s/g 和 /\\s+/g 之间有区别吗?

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

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' ).我们想从字符串中删除空格(我们想要这个: '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.更新:性能比较 - /\\s+/g更快。 See here: http://jsperf.com/s-vs-s见这里: http : //jsperf.com/s-vs-s

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.然而,就像 0 乘以其他任何东西是 0 一样,这两种方法似乎以完全相同的方式去除空格。

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". \\s表示“一个空格”,而\\s+表示“一个或多个空格”。

But, because you're using the /g flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect.但是,因为您使用/g标志(替换所有出现的)并替换为空字符串,所以您的两个表达式具有相同的效果。

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.例如,如果您将其替换为 'x',结果会有所不同。

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

while str.replace(/\\s+/g, 'x') will return 'xAxBxCxDxEF 'str.replace(/\\s+/g, 'x')将返回 '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'.因为\\s匹配每个空格,用'x' 替换每个空格,而\\s+匹配空格组,用单个'x' 替换多个连续的空格。

+ means "one or more characters" and without the plus it means "one character." +表示“一个或多个字符”,没有加号则表示“一个字符”。 In your case both result in the same output.在您的情况下,两者都会产生相同的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM