正则表达式/_/g是什么意思?

时间:2022-12-26 15:46:32

javascript:

javascript:

.replace(/_/g," ");

I have it in my code but can't remember why or what it does! Can one of you regular expression gurus help? I know this may seem basic, but regular expressions are not my cup of tea, and googling for /g won't help much...

我的代码中有它,但不记得它是怎么做的!你们中的一个正则表达式大师能帮上忙吗?我知道这看起来很简单,但是规则的表达方式并不是我喜欢的,搜索/g也没什么用……

3 个解决方案

#1


118  

The regex matches the _ character.

regex匹配_字符。

The g means Global, and causes the replace call to replace all matches, not just the first one.

g表示全局,并导致replace调用替换所有匹配,而不仅仅是第一个匹配。

#2


22  

Like everyone else has said, it replaces all underscores with spaces. So "Hello_there." would become "Hello there."

就像其他人说的那样,它用空格替换了所有的下划线。所以"Hello_there "会变成"Hello there "

But along with the answer, I want to suggest something to you. Use comments.

除了答案,我还想给你提点建议。使用注释。

In your code say something like:

在你的代码中可以这样写:

// Replaces all underscores so that blah blah blah blah blah..
var hello = "Hello_there."
    .replace(/_/g, ' ');

#3


2  

Returns a new string with all the underscores in the source string replaced with spaces.

返回一个新的字符串,在源字符串中所有下划线替换为空格。

#1


118  

The regex matches the _ character.

regex匹配_字符。

The g means Global, and causes the replace call to replace all matches, not just the first one.

g表示全局,并导致replace调用替换所有匹配,而不仅仅是第一个匹配。

#2


22  

Like everyone else has said, it replaces all underscores with spaces. So "Hello_there." would become "Hello there."

就像其他人说的那样,它用空格替换了所有的下划线。所以"Hello_there "会变成"Hello there "

But along with the answer, I want to suggest something to you. Use comments.

除了答案,我还想给你提点建议。使用注释。

In your code say something like:

在你的代码中可以这样写:

// Replaces all underscores so that blah blah blah blah blah..
var hello = "Hello_there."
    .replace(/_/g, ' ');

#3


2  

Returns a new string with all the underscores in the source string replaced with spaces.

返回一个新的字符串,在源字符串中所有下划线替换为空格。