What does the regular expression /_/g mean?

JavascriptRegex

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

The regex matches the _ character.

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

Solution 2 - Javascript

Like everyone else has said, it replaces all underscores with spaces. So "Hello_there." would become "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, ' ');

Solution 3 - Javascript

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

Solution 4 - Javascript

we can use the expression / /g to search or extract a pattern more than once, you can use the g flag.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomView Question on Stackoverflow
Solution 1 - JavascriptSLaksView Answer on Stackoverflow
Solution 2 - JavascriptMcKaylaView Answer on Stackoverflow
Solution 3 - JavascriptRoy TinkerView Answer on Stackoverflow
Solution 4 - JavascriptHamza SayihView Answer on Stackoverflow