TutreNews Learn

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.

questionmethodresult
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)
Replaces.replace(re, text)new string (only the first match without g; replaceAll needs g)
Split into partss.split(re)array of strings

Tips:

  • match with g returns null (not an empty array) when nothing matches. Guard with ?? [].
  • replace accepts a function as second argument for computed replacements: "3 4".replace(/\d/g, d => d * 2) gives "6 8".
  • A regex with the g flag keeps state in lastIndex when used with test repeatedly. Avoid reusing a global regex for several test calls.
  • split(/\s+/) splits at any run of whitespace, which is more robust than split(" ").

Worked example: Extracting all numbers

  1. Text: "3 apples, 12 pears, 7 plums".
  2. text.match(/\d+/g) returns ["3", "12", "7"].
  3. 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