What's the meaning of /gi in a regex?

JavascriptRegex

Javascript Problem Overview


I see an line in my JavaScript code like this:

var regex = /[^\w\s]/gi;

What's the meaning of this /gi in the regex?

Other part I can understand as it accepts a group of word and spaces, but not /gi.

Javascript Solutions


Solution 1 - Javascript

g modifier: global. All matches (don't return on first match)

i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

In your case though i is immaterial as you dont capture [a-zA-Z].

For input like !@#$ if g modifier is not there regex will return first match !See here.

If g is there it will return the whole or whatever it can match.See here

Solution 2 - Javascript

The beginning and ending / are called delimiters. They tell the interpreter where the regex begins and ends. Anything after the closing delimiter is called a "modifier," in this case g and i.

The g and i modifiers have these meanings:

  • g = global, match all instances of the pattern in a string, not just one
  • i = case-insensitive (so, for example, /a/i will match the string "a" or "A".

In the context you gave (/[^\w\s]/gi), the i is meaningless, because there are no case-specific portions of the regex.

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
QuestionbatmanView Question on Stackoverflow
Solution 1 - JavascriptvksView Answer on Stackoverflow
Solution 2 - JavascriptelixenideView Answer on Stackoverflow