Regex in practice
Regex methods in JavaScript
Goal: Choose between test, match, matchAll, replace and split · 10 min
JavaScript offers a handful of methods. Pick the one that answers your question.
| question | method | result |
|---|---|---|
| Does it match? | re.test(s) | true / false |
| What is the first match (with groups)? | s.match(re) | match array or null |
| What are all matches (without groups)? | s.match(/…/g) | array of strings or null |
| All matches with groups? | [...s.matchAll(/…/g)] | array of match arrays (needs g) |
| Replace | s.replace(re, text) | new string (only the first match without g; replaceAll needs g) |
| Split into parts | s.split(re) | array of strings |
Tips:
matchwithgreturnsnull(not an empty array) when nothing matches. Guard with?? [].replaceaccepts a function as second argument for computed replacements:"3 4".replace(/\d/g, d => d * 2)gives "6 8".- A regex with the
gflag keeps state inlastIndexwhen used withtestrepeatedly. Avoid reusing a global regex for severaltestcalls. split(/\s+/)splits at any run of whitespace, which is more robust thansplit(" ").
Worked example: Extracting all numbers
- Text: "3 apples, 12 pears, 7 plums".
text.match(/\d+/g)returns ["3", "12", "7"].- Map to numbers and add them: 22.
const text = "3 apples, 12 pears, 7 plums";
const nums = text.match(/\d+/g).map(Number);
console.log(JSON.stringify(nums), nums.reduce((a, b) => a + b, 0));Output:
[3,12,7] 22