/ \s / g和/ \s + / g之间有区别吗? [英] Is there a difference between /\s/g and /\s+/g?

查看:276
本文介绍了/ \s / g和/ \s + / g之间有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们有一个包含空格字符的字符串时:

When we have a string that contains space characters:

var str = '  A B  C   D EF ';

我们想从字符串中删除空格(我们想要这个: 'ABCDEF')。

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

这两个:

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

并且:

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

将返回正确的结果。

这是否意味着 + 在这种情况下是多余的?在这种情况下,这两个正则表达式之间是否存在差异(例如,它们是否会以任何方式产生不同的结果)?

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)?

更新:效果比较 - / \s + / g 更快。请参阅此处: http://jsperf.com/s-vs-s

Update: Performance comparison - /\s+/g is faster. See here: 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 +.

但是,就像0乘以其他任何值为0一样,似乎两种方法都以完全相同的方式去除空格。

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 / g和/ \s + / g之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆