Find regex matches in JavaScript with match()

text.match(regex) searches a JavaScript string with a regular expression. Without g, it returns the first match and its details. With g, it returns all matched strings. A failed search returns null in both cases.

Read the first match and handle null

Without g, read the full match at [0] and its starting position in index. Check for null first, or use optional chaining such as found?.[0] if you want undefined for a missing value. See String.prototype.match().

const text = 'Lorem Ipsum Dolor';
const found = text.match(/Lo/);
console.log(found[0]);     // 'Lo'
console.log(found.index);  // 0

const absent = text.match(/Loi/);
console.log(absent);       // null
console.log(absent?.[0]);  // undefined

Combine g, i, and capture groups

i matches letters without case distinctions in the example. Capturing parentheses return group values at [1] and later indexes when g is absent. With g, the strings are returned without per-match indexes or captures. Here \w matches the English letters after Lo. It is unsuitable as a general pattern for all Unicode letters.

const text = 'Lorem Ipsum Dolor';
console.log(text.match(/lo/i)[0]);    // 'Lo'
console.log(text.match(/o/g));        // ['o', 'o', 'o']

const captured = text.match(/Lo(\w+)/);
console.log(captured[0]); // 'Lorem'
console.log(captured[1]); // 'rem'
console.log(captured.index); // 0

Try a complete match() example

Save the full example as match-example.html in UTF-8 and open it. The list uses fixed patterns so you can change flags and capture groups without writing a new expression each time.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Compare String.match results</title>
</head>
<body>
<label for="source">Text to search</label>
<input id="source" type="text" value="Lorem Ipsum Dolor">
<label for="pattern">Regular expression</label>
<select id="pattern">
  <option value="first">/Lo/ First match</option>
  <option value="insensitive">/lo/i Ignore case</option>
  <option value="all">/o/g All matches</option>
  <option value="capture">/Lo(\w+)/ Capture</option>
  <option value="missing">/Loi/ No match</option>
</select>
<button id="search" type="button">Search</button>
<button id="reset" type="button">Reset</button>
<pre id="output" aria-live="polite"></pre>
<script>
const patterns = {
  first: /Lo/,
  insensitive: /lo/i,
  all: /o/g,
  capture: /Lo(\w+)/,
  missing: /Loi/
};
const source = document.querySelector('#source');
const choice = document.querySelector('#pattern');
const output = document.querySelector('#output');

function show() {
  const regex = patterns[choice.value];
  const result = source.value.match(regex);
  if (result === null) {
    output.textContent = 'No match: null';
  } else if (regex.global) {
    output.textContent = `All matched strings: ${JSON.stringify(result)}`;
  } else {
    const captured = result.length > 1 ? result.slice(1).join(', ') : 'None';
    output.textContent = `First match: ${result[0]}\nStart index: ${result.index}\nCapture: ${captured}`;
  }
}

document.querySelector('#search').addEventListener('click', show);
document.querySelector('#reset').addEventListener('click', () => {
  source.value = 'Lorem Ipsum Dolor';
  choice.value = 'first';
  show();
});
show();
</script>
</body>
</html>

Initially you get Lo at 0. /o/g returns three occurrences of o. /Lo(\w+)/ returns Lorem with the capture rem. /Loi/ returns null. Edit the text to compare results, and reset to restore the starting text and pattern.

Choose match(), matchAll(), or a simpler test

Use test() for a yes-or-no regex check without g or y when repeating the check. Use indexOf() for the position of plain text. Use matchAll() when you need details for each match.

The two named groups in this example capture a letter and a number. Global match() gives only the matched strings. Iterating over matchAll() also gives each start index and both group values.

{
  const text = 'A-17 B-42';
  const pattern = /(?<code>[A-Z])-(?<number>\d+)/g;

  console.log(text.match(pattern)); // ['A-17', 'B-42']

  for (const match of text.matchAll(pattern)) {
    console.log(match[0], match.index, match.groups.code, match.groups.number);
  }
  // A-17 0 A 17
  // B-42 5 B 42
}

The last two lines are A-17 0 A 17 and B-42 5 B 42. A RegExp passed to matchAll() needs g, otherwise the call throws TypeError. Use Array.from() if you need an array of the iterator’s results. See String.prototype.matchAll().