JavaScript Regex Flags


You can specify one or more flags in a regular expression after the second slash in case of a literal regular expression like in /[aeiou]+)/i or as a second string argument in case of a Regex object. JavaScript regex has 8 flags all of which are single lettered g, i, m, s, u, v, y, d. The flags can occur in any order and in any combination except the 'u' and 'v' flags cannot occur together in the same regex.

The 'g' flag:

It declares the regular expression as global which tells the regex engine to find all matches in the target string rather than just the first one

The ‘i' Flag

The regex engine must consider case insensitive matches too

The 'm' Flag

The regular expression is in ‘multiline’ mode. When used with a string containing multiple lines, the '^' and '$' operators must match both the beginning and end of the string as well as the beginning and end of each line.

The 's' Flag

The 's' flag is useful when the target string contains new lines. Without the 's' flag, the '.' operator matches all characters except the new line. With the 's' flag, the '.' operator matches all characters including the new line

The 'u' Flag

The 'u' stands for unicode. JavaScript strings are encoded in UTF-16. Emojis and other characters are more than 16 bit long. They are represented as two 16-bit surrogate pair. Without the 'u' flag, they are incorrectly treated as 2 separate characters instead as one. Always use the 'u' flag unless you have a very good reason not to. You can use the \u{...} escape sequence for Unicode characters. Enables the use of \p{...} to match characters based on their Unicode properties.

The 'v' Flag

The 'v' enables the ‘unicodeSets’ mode. It is an improvement over the 'u' flag. Some of its features are not compatibable with the 'u' flag, so both flags cannot be used at the same time which results in an error. The 'v' flag supports extended character classes like

  • Unicode properties of strings
  • Set notation + string literal syntax
  • Improved case-insensitive matching

The 'd' Flag

The 'd' flag tells the regex engine to generate ‘indices’ which are start and end positions for matches. The returned value of exec(), match(), matchAll() etc will contain an indices property

The 'y' Flag

The 'y' flag is also known as the ‘sticky’ flag. With the sticky flag on, the Regex engine tries to find the next match at the lastIndex property of the RegExp object. After a match is found, the lastIndex is advanced to the end of the match.

We will study each of the flags in greater detail in subsequent pages,