JS: RegExp Flag

By Xah Lee. Date: . Last updated: .

What is Regex Flag

List of Regex Flags

RegExp.prototype.global

g

Find all matches.

Used by many JS: Regex Functions

RegExp.prototype.ignoreCase

i

Ignore case.

RegExp.prototype.multiline

m
  • Make the RegExp syntax ^ match any newline beginning. (instead of the beginning of whole string)
  • Make the RegExp syntax $ match any newline end. (instead of the end of whole string)
console.log(/^B/.test("A\nB") === false);
console.log(/^B/m.test("A\nB") === true);

RegExp.prototype.dotAll

s

(JS2018) Make the dot . also match newline characters. γ€”see RegExp Syntax〕

console.log(/A.B/.test("A\nB") === false);
console.log(/A.B/s.test("A\nB") === true);

RegExp.prototype.unicode

u

(JS2015) Treat string as sequence of unicode characters. (as opposed to being JS: String Code Unit)

  • πŸ’‘ TIP:
  • It's a good idea to always have this flag on.
  • This flag is useful to prevent matching a surrogate pair code unit in input string. γ€”see JS: String Code Unit〕 It's not for β€œenabling” matching Unicode. (Unicode characters are matched always.)
  • To match Unicode character properties, use unicode propery character class syntax. γ€”see RegExp Unicode Property〕
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 πŸ˜‚

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.

πŸ˜‚
FACE WITH TEARS OF JOY
codepoint 128514
codepoint in hexadecimal 1f602
bytes in UTF-16: D8 3D DE 02

 */

RegExp.prototype.sticky

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.)

JavaScript, Regular Expression