CKTIS / JavaScript
RegExp flags g/i/m/u and Unicode property escapes
Learn how global, case-insensitive, multiline, and Unicode-aware matching work together, and how to match letters or other characters by Unicode property.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
/pattern/gimu
new RegExp(patternString, "gimu")
/\p{Letter}/u
/\P{Letter}/u
/\p{Script_Extensions=Greek}/u
new RegExp("\\p{Letter}", "u")Put flags after the closing slash in /pattern/gimu or pass them as the second argument to new RegExp(patternString, "gimu"). In an ordinary JavaScript string literal, double the backslash: new RegExp("\\p{Letter}", "u"). Duplicate or unrecognized flags cause a SyntaxError.
g means global search: text.match(re) returns all full matches, or null if there are none. Each exec() or test() call still looks for just one match. With g, it searches from lastIndex, sets it to the end of the match on success, and resets it to 0 on failure. lastIndex counts UTF-16 code units even with u. Before reusing a global regex for an independent search, reset lastIndex to 0 or create a new regex.
i ignores case without locale-specific rules; with u, it uses Unicode simple case folding. m lets ^ also match just after a line terminator and $ just before one. It does not make . match line terminators; that is what s does. u enables Unicode code-point matching and stricter pattern syntax. A code point is not necessarily a whole user-perceived character.
In u mode, \p{L} matches a code point in the Letter category, and \P{L} matches its complement when i is absent. You can also use a name–value pair, as in \p{Script_Extensions=Greek}. Supported names, values, and aliases are case-sensitive; invalid ones cause a SyntaxError in Unicode-aware mode. Without u or v, \p and \P stand for literal p and P. The v flag also supports property escapes but cannot be combined with u. Check support in your target runtime.
Examples
const text = "TAG:É\nTag:\u{10400}\nTAG:7\nxTag:Ω";
console.log(JSON.stringify(text.match(/^tag:\p{L}$/gimu)));Result
["TAG:É","Tag:𐐀"]
`g` collects both matches, `i` accepts `TAG` and `Tag`, and `m` applies the anchors at line boundaries. With `u`, `\p{L}` matches `É` and `𐐀` as single code points. The line with `7` fails because a digit is not a letter, and `xTag:Ω` does not start with `tag:`.
Related lessons
- JavaScript · Lesson 25 · Intermediate · Version: 3
Sources
- ECMAScript 2024 Language Specification — Patterns
- ECMAScript 2024 Language Specification — RegExpInitialize
- ECMAScript 2024 Language Specification — RegExpBuiltinExec
- ECMAScript 2024 Language Specification — RegExp.prototype [ @@match ]
- Unicode character class escape: \p{...}, \P{...} — MDN
- RegExp() constructor — MDN