JS: RegExp Flag
Regex flags change the meaning of the regular expression, or behavior of Regex Functions . For how to add them, see JS: RegExp Syntax
RegExp Flags
g
(State stored inRegExp.prototype.global
)-
Find all matches.
Used by many Regex Functions
i
(State stored inRegExp.prototype.ignoreCase
)-
Ignore case.
m
(State stored inRegExp.prototype.multiline
)-
- 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);
- Make the RegExp syntax
u
(State stored inRegExp.prototype.unicode
)-
(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.
π‘ TIP: 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.)
π‘ TIP: 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 */
y
(State stored inRegExp.prototype.sticky
)-
(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.) -
s
(State stored inRegExp.prototype.dotAll
) -
(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);
JavaScript, Regular Expression
- JS: RegExp Tutorial
- JS: Regex Functions
- JS: RegExp Syntax
- JS: RegExp Flag
- JS: Regex Replace String Dollar Sign
- JS: Regex Replace Function Args
- JS: RegExp Object
- JS: RegExp Constructor
- JS: RegExp.prototype
- JS: String.prototype.search
- JS: String.prototype.match
- JS: String.prototype.matchAll
- JS: String.prototype.replace
- JS: String.prototype.replaceAll
- JS: RegExp.prototype.test
- JS: RegExp.prototype.exec