What does the regular expression /_/g mean?
Asked Answered
E

4

124

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.

Ebracteate answered 19/5, 2011 at 0:45 Comment(1)
just to add.. you can use / /gi to make it case-insensitive! Sometimes you want to change words in a string or a paragraph, but it happens that some of them are in the beginning of a sentence, so they're in most of the cases capitalized, if you use only the g it would replace only let say "Angels" and forgets about "angels" or vice versa, it depends on what you put as arguments. ps: This works with the replace() method in JavaScript.Serpentiform
Z
188

The regex matches the _ character.

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

Zacharia answered 19/5, 2011 at 0:48 Comment(1)
the hyperlink is obsolete, please include the quoted text next timeFleer
W
37

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, ' ');
Wrap answered 19/5, 2011 at 1:4 Comment(0)
S
3

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

Sorcerer answered 19/5, 2011 at 0:54 Comment(0)
W
3

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

Windbroken answered 10/3, 2021 at 12:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.