match, test, replace in JavaScript
In JavaScript, regex.test(str) returns true or false; str.match(regex) returns the first match with its groups, or all matches as plain strings with the g flag; str.matchAll(regex) iterates every match with groups; str.replace(regex, replacement) substitutes (all of them with g); str.split(regex) splits; regex.exec(str) is match plus a lastIndex cursor for loops.
Syntax
re.test(s) s.match(re) s.matchAll(re) s.replace(re, rep) s.split(re) re.exec(s) s.search(re)| Part | What it is |
|---|---|
test | boolean: does the pattern occur anywhere |
match | array with groups (no g), or array of all matches (g), or null |
matchAll | iterator of match arrays with groups; requires g |
replace | new string; replacement may use $1, $<name>, $& or a function |
split | array of pieces; captured groups are included in the output |
exec | like match without g, but advances lastIndex when the regex has g |
Examples
/\d/.test("a1")Result: true
["a1b22".match(/\d+/)[0], "a1b22".match(/\d+/g)]Result: ["1", ["1", "22"]]
Without g, the first match (with groups); with g, every match as strings.
[..."a=1;b=2".matchAll(/(\w)=(\d)/g)].map(m => m[1] + ":" + m[2])Result: ["a:1", "b:2"]
"2024-03-15".replace(/(\d+)-(\d+)-(\d+)/, (m, y, mo, d) => d + "." + mo + "." + y)Result: "15.03.2024"
A replacer function receives the whole match, then each group.
Common mistakes
- Using match with g and then reading m[1]: with g there are no groups, only whole matches. Use matchAll.
- Calling matchAll with a regex that lacks the g flag; it throws a TypeError.
- Expecting replace to change every occurrence without g, or passing a non-g regex to replaceAll, which throws.
- Forgetting the special replacement patterns: $& is the whole match, $$ a literal dollar, $1 a group.
Practice match, test, replace in JavaScript
These drills check your answer on live data, free, no account needed.
- Capture a standalone yearCapture the first standalone four-digit number on each line in group 1. Digits that are part of a longer number do not count. Lines without one give no match.
- Swap Last, First to First LastLines that are exactly Last, First become First Last. Names contain letters, apostrophes and hyphens. Leave other lines unchanged.
- key=value pairsLines hold key=value pairs separated by semicolons. Capture every pair: the key (word characters) in group 1 and the value (everything up to the next semicolon, possibly empty) in group 2.
Questions
How do I check if a string matches a regex in JavaScript?
Use regex.test(str) for a boolean. Anchor the pattern with ^ and $ if the whole string must match; test alone succeeds when the pattern appears anywhere.
How do I get all matches with their groups?
Use [...str.matchAll(/pattern/g)]; each item is a match array with index 0 as the full match, numbered groups after it, and .groups for named groups.
What does match return when nothing matches?
null, both with and without the g flag. Guard with (str.match(re) || []) when you want to iterate the result directly.
Related
- Regex flagsWhat each JavaScript regex flag does (case-insensitive, global, multiline, dotAll, unicode, sticky), how to set them, and the lastIndex trap with g and test.
- Capture groupsHow parentheses capture text, reading groups in JavaScript via match, matchAll and exec, reusing them with $1 in replace, and the g trap that loses groups.
- Named groups (?<name>...)How to capture by name, read match.groups.name, use $<name> in replacements and \k<name> as a backreference, and the (?P<name>) syntax Python needs.
- Escaping special charactersThe regex metacharacters that must be escaped, how to match a literal dot, dollar, plus or slash, what changes inside brackets, and how to escape user input.