Regex flags explained: g, i, m, s, u, y
Two patterns can be character for character identical and still behave completely differently, because the flags attached to them change the rules of the match. Flags are the modifiers that sit after the closing slash, like /pattern/gi, and each one toggles a distinct behavior.
The six flags
Here is what each does, with the JavaScript letter. Most engines share the concepts even where the syntax differs.
gglobal. Find all matches, not just the first. Without it, a replace touches one occurrence; with it, every occurrence. It also makes the engine track a position between calls, which matters for iteration.iignore case.Amatchesa. The most common and least surprising flag.mmultiline. Changes^and$to match at the start and end of each line, not only the whole string. Covered in anchors and multiline mode.sdotall. Lets.match newline characters too. By default.matches any character except a line break; withsit truly matches any character.uunicode. Treats the pattern as a sequence of Unicode code points rather than UTF-16 code units, and enables property escapes like\p{L}. Needed to handle characters outside the basic plane, such as many emoji.ysticky. Anchors each match attempt to the engine's current position. The match must start exactly there or it fails, with no scanning ahead. Useful for writing tokenizers that consume input left to right.
Flags people confuse
Three pairs cause most of the confusion:
mis nots. Multiline changes what the anchors mean. Dotall changes what.matches. They are independent and often used together,ms, when scanning a block of text line sensitive but also allowing.to cross lines inside a group.gchanges replace, and iteration state. Withg,String.replaceswaps every match. Without it, only the first. And agoryregex object rememberslastIndexbetweenexeccalls, which is why reusing one in a loop needs care.uis opt in. Without it,.and\wthink in UTF-16 units, so an emoji can be two half matches. Adduwhenever your input is real world text.
Common combinations
/error/gi all matches, any case
/^\s*#/m comment line, any line in the block
/".*?"/gs quoted strings that may span lines
/\p{L}+/gu runs of letters in any language
Seeing the effect
The fastest way to build intuition is to flip a flag and watch the highlights change. In the Regex Tester the flag toggles sit next to the pattern, so you can turn g on to light up every match or add s to let a greedy . jump a newline. Everything runs in your browser, so the sample text never leaves your device.
The takeaway: a pattern is only half the specification; the flags are the other half. Learn the six, watch for the m and s mix up, and always add u when the text is human language rather than ASCII.