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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6052616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:03:04  来源:igfitidea点击:

What does the regular expression /_/g mean?

javascriptregex

提问by Tom

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 /gdidn't help much.

我知道这可能看起来很基本,但正则表达式不是我的菜,谷歌搜索/g也没有多大帮助。

回答by SLaks

The regex matches the _character.

正则表达式匹配_字符。

The gmeans Global, and causes the replacecall to replace all matches, not just the first one.

g意味着Global,并导致replace调用替换所有匹配项,而不仅仅是第一个匹配项。

回答by McKayla

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, ' ');

回答by Roy Tinker

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

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