JS: RegExp Flags

By Xah Lee. Date: . Last updated: .

Regex flag changes the meaning of the RegExp Syntax , or the behavior of the Regex Functions .

Flags

g
Find all matches. Don't stop after first found. Used by String.prototype.match, String.prototype.matchAll, String.prototype.replace and others.
State stored in RegExp.prototype.global.
i
Ignore case. Example: "WATER".search( /t/i ).
State stored in RegExp.prototype.ignoreCase.
m
Make the RegExp syntax ^ and $ match any newline beginning/end. (instead of the beginning/end of whole string)
State stored in RegExp.prototype.multiline.
console.log(/^B/.test("A\nB")); // false
console.log(/^B/m.test("A\nB")); // true
u
(JS2015) Treat string as sequence of unicode characters. If your string contains a character whose codepoint is ≥ 2^16, such as emoji, you shoud set this flag. It's a good idea to always have this flag on.

(Tip: this flag is useful to prevent matching a code unit in input string. [see Character, Code Unit, Codepoint] It's not for enabling matching unicode. To match Unicode characters, use unicode propery syntax. See RegExp Unicode Property )
State stored in RegExp.prototype.unicode.
console.log(/\ud83d/.test("😂")); // true
console.log(/\ud83d/u.test("😂")); // false

// U+D83D is not a valid unicode character. D83D is hexadecimal of first code unit of a surrogate pair for 😂

/* [
😂
FACE WITH TEARS OF JOY
codepoint 128514
codepoint in hex 1f602
bytes in UTF-16: D8 3D DE 02
So in JavaScript , the char is made up of 2 code units: D83D DE02
When you search for D83D without unicode flag, it returns true.
but with unicode flag, it returns false.
] */
y
(JS2015) Make the match start at the index RegExp.prototype.lastIndex. (does not change the meaning of ^. It still mean beginning of string or line.)
State stored in RegExp.prototype.sticky.
s
(JS2018) Make the dot . also match newline characters. [see RegExp Syntax]
State stored in RegExp.prototype.dotAll.
console.log(/A.B/.test("A\nB")); // false
console.log(/A.B/s.test("A\nB")); // true
JS in Depth
XAH
Buy Xah JavaScript Tutorial
JS in Depth
XAH

JS Obj Ref

DOM


JS Obj Ref

RegExp

prototype

Syntax

misc