What does the regular expression /_/g mean?

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

133148 次浏览

The regex matches the _ character.

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

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

正如其他人所说,它用空格替换所有的下划线。因此 "Hello_there."将成为 "Hello there."

但是除了答案,我还想给你一些建议。

在您的代码中,可以这样说:

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

我们可以使用表达式 / /g多次搜索或提取一个模式,可以使用 g 标志。