JS: Regular Expression Flags
What is regex flag
- Regex flags change the meaning of the regular expression, or behavior of Regex Functions.
- For how to add them, see JS: Create Regex Object.
RegExp.prototype.global • g
- Property Name:
RegExp.prototype.global - Short Code:
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
- Property Name:
RegExp.prototype.ignoreCase - Short Code:
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
- Property Name:
RegExp.prototype.multiline - Short Code:
m
- Make the regex syntax
^match any newline beginning. (instead of the beginning of whole string) - Make the regex syntax
$match any newline end. (instead of the end of whole string)
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)
- Property Name:
RegExp.prototype.dotAll - Short Code:
s
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)
- Property Name:
RegExp.prototype.unicode - Short Code:
u
Interpret the text to be matched as byte sequence of characters of their unicode code points.
RegExp.prototype.sticky • y
(new in ECMAScript 2015)
- Property Name:
RegExp.prototype.sticky - Short Code:
y
Make the match start at the index RegExp.prototype.lastIndex.
(does not change the meaning of ^. It still mean beginning of string or line.)