TutreNews Learn

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.

flagnameeffect
iignore case"Cat", "cat" and "CAT" are equal
gglobalfind all matches, not just the first
mmultiline^ and $ match at every line start and end
sdotAll. also matches line breaks
uunicodefull 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

  1. Text: "Tea tea TEA".
  2. Without flags /tea/ finds nothing useful: only the lowercase one.
  3. With g and i all three are found.
const s = "Tea tea TEA";
console.log(s.match(/tea/g).length, s.match(/tea/gi).length);

Output:

1 3