Groups, choices and lazy matching
Flags
Goal: Change matching behaviour with the flags i, g, m and s · 7 min
Flags go after the closing slash and change how the whole pattern behaves.
| flag | name | effect |
|---|---|---|
i | ignore case | "Cat", "cat" and "CAT" are equal |
g | global | find all matches, not just the first |
m | multiline | ^ and $ match at every line start and end |
s | dotAll | . also matches line breaks |
u | unicode | full Unicode support, enables \p{L} for any letter |
Flags combine: /hello/gi. With the constructor: new RegExp("hello", "gi"). In that form, backslashes in the string must be doubled: new RegExp("\\d+").
Tip for German text: /\p{L}+/gu matches words with umlauts and ß, which \w+ cannot.
Worked example: Counting words case-insensitively
- Text: "Tea tea TEA".
- Without flags
/tea/finds nothing useful: only the lowercase one. - With
gandiall three are found.
const s = "Tea tea TEA";
console.log(s.match(/tea/g).length, s.match(/tea/gi).length);Output:
1 3