JS: Regular Expression Flags

By Xah Lee. Date: . Last updated: .

What is regex flag

RegExp.prototype.global • g

Find all matches.

Used by some regex functions. e.g. String.prototype.match • String.prototype.replace

// demo diff of regex flag g

/* get all occurrence of a match */
console.log("something".match(/[aeiou]/g));
// [ "o", "e", "i" ]

console.log("something".match(/[aeiou]/));
// [ "o", index: 1, input: "something", groups: undefined ]
// RegExp.prototype.global
const regexobj = /([aeiou])/g;
console.assert(regexobj.global === true);

RegExp.prototype.ignoreCase • i

Ignore case.

// demo diff of ignoreCase

console.assert(/a/i.test("ABC"));

console.assert(/a/.test("ABC") === false);
const xx = /a/i;
console.assert(xx.ignoreCase);

RegExp.prototype.multiline • m

console.assert(/^B/.test("A\nB") === false);
console.assert(/^B/m.test("A\nB"));
console.assert(/a/m.multiline);

RegExp.prototype.dotAll • s

(new in ECMAScript 2018)

Make the dot . also match newline characters. [see RegExp Syntax]

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

RegExp.prototype.unicode • u

(new in ECMAScript 2015)

Interpret the text to be matched as byte sequence of characters of their unicode code points.

RegExp.prototype.sticky • y

(new in ECMAScript 2015)

Make the match start at the index RegExp.prototype.lastIndex. (does not change the meaning of ^. It still mean beginning of string or line.)