Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 327
Tom Avatar asked May 19 '11 00:05

Tom


People also ask

What does G mean in regular expression?

The " g " flag indicates that the regular expression should be tested against all possible matches in a string. A regular expression defined as both global (" g ") and sticky (" y ") will ignore the global flag and perform sticky matches. You cannot change this property directly.

What does /\ s +/ g mean?

\s means "one space", and \s+ means "one or more spaces". But, because you're using the /g flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect. Follow this answer to receive notifications.

What is g modifier in regex?

The "g" modifier specifies a global match. A global match finds all matches (compared to only the first).

What is +/ g'in JavaScript replace?

replace in JavaScript will only replace the first matching value it finds. Adding the /g will mean that all of the matching values are replaced. Show activity on this post. The "g" that you are talking about at the end of your regular expression is called a "modifier".


1 Answers

The regex matches the _ character.

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

like image 53
SLaks Avatar answered Sep 22 '22 08:09

SLaks