JavaScript Reference Β· RegExp
Regular expression flags
Reference for JavaScript regular expression flags: what g, i, m, s, u, v, y and d do, how they combine, and how to read them from the flags property.
Flags are single letters after the closing slash of a regex literal (/pattern/gi) or in the second argument of new RegExp(). They change how the pattern is matched: whether it finds every match, ignores case, treats lines separately, understands Unicode, and so on.
There are eight flags. Order does not matter; reading regex.flags always lists the ones that are set in a fixed order, dgimsuvy. This is a concept page: each flag is explained below with live examples.
const regex = /hello/gi; regex.flags; // "gi" regex.global; // true regex.ignoreCase; // true
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
The flags
| Flag | Property | Meaning |
|---|---|---|
d |
hasIndices |
Adds an indices array with the start and end of each group to match results. |
g |
global |
Finds all matches. Makes exec() and test() stateful through lastIndex. Required by replaceAll() and matchAll(). |
i |
ignoreCase |
Ignores differences in letter case. |
m |
multiline |
^ and $ match at line starts and ends, not only at the string's ends. |
s |
dotAll |
. also matches line terminators. |
u |
unicode |
Treats the pattern and text as code points, and enables \u{...} and \p{...}. Stricter syntax. |
v |
unicodeSets |
An upgrade of u with set subtraction (--), intersection (&&) and string properties. Cannot be combined with u. |
y |
sticky |
Matches only at the position in lastIndex, never later. |
Usage notes
gchanges how methods behave.match()withgreturns all matched strings (without groups), andreplace()withgreplaces every match.matchAll()andreplaceAll()throw aTypeErrorif the regex lacksg.- Use
uorvfor emoji and non-Latin text, or.will match half a surrogate pair. Prefervin new code where supported. - Without
s,.skips\n,\r,β¨andβ©. A common workaround is[\s\S]. mdoes not change.. It affects only the anchors^and$.iwithuuses full Unicode case folding, so a few more characters match each other.- Unknown or repeated flags throw a
SyntaxErrorwhen the regex is created, anduwithvis an error. - Flags are fixed. The properties are read-only; to change flags make a new regex with
new RegExp(regex, "newflags"). - Sticky vs anchored:
yanchors atlastIndex,^at the start of the string (or line). They are different tools.
Browser support
g, i, m and y and u are supported everywhere modern. s and d are newer and the v flag is the most recent, so check a compatibility table; the v example above uses a try/catch for that reason.
Related
RegExp,exec(),lastIndex- character classes, anchors
- Lesson: Regular Expressions