Count the Number of Regex Matches using JavaScript

avatar

Borislav Hadzhiev

2 min

banner

Photo from Unsplash

Count the Number of Regex Matches in JavaScript #

To count the number of regex matches:

  1. Use the String.match() method to match a string against a regular expression.
  2. The match() method returns an array of regex matches.
  3. Access the length property on the array.
index.js
const str = 'one two one one'; const count = (str.match(/one/g) || []).length; console.log(count); // ๐Ÿ‘‰๏ธ 3

The String.match method matches a string against a regular expression.

The method returns an array containing the matches (if any) or null if no matches are found.

The forward slashes / / mark the beginning and end of the regular expression.

In the example, we search for the substring one.

Notice that we used the g (global) flag after the regex. The g flag allows us to match all occurrences of the regular expression in the string and not just the first occurrence.

If no matches of the regex are found in the string, the match() method returns null.

We used the logical OR (||) operator to provide a fallback value of an empty array because accessing the length property on a null value would cause an error.

index.js
const str = 'one two one one'; const count = (str.match(/one/g) || []).length; console.log(count); // ๐Ÿ‘‰๏ธ 3

The logical OR (||) operator returns the value to the right if the value to the left is falsy.

The falsy values are: null, undefined, false, 0, "" (empty string), NaN (not a number).

All other values are truthy.

Common regular expressions #

Here are some examples of commonly used regular expressions.

index.js
// โœ… Any digit 0-9 const str = '123 hello 123'; const count = (str.match(/[0-9]/g) || []).length; console.log(count); // ๐Ÿ‘‰๏ธ 6 // โœ… Any Alphanumeric character const str2 = '123 hello !@#$%^&'; const count2 = (str2.match(/[a-zA-Z0-9]/g) || []).length; console.log(count2); // ๐Ÿ‘‰๏ธ 8 // โœ… Any latin letters const str3 = 'Hello 123'; const count3 = (str3.match(/[a-zA-Z]/g) || []).length; console.log(count3); // ๐Ÿ‘‰๏ธ 5 // โœ… Occurrences of a, b or c const str4 = 'abc123abc'; const count4 = (str4.match(/[abc]/g) || []).length; console.log(count4); // ๐Ÿ‘‰๏ธ 6

The square brackets in the regular expression allow us to match ranges e.g. digit ranges - [0-9], or letter ranges - [a-zA-Z].

They also allow us to match either one of multiple characters, e.g. [abc] matches a, b, or c.

Make sure you use the g (global) flag because if you don't, the regex would match only the first occurrence.

If you ever need help reading a regular expression, check out this regular expression cheatsheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

Count the Number of Regex Matches using RegExp.exec() #

You can also use the RegExp.exec method to count the number of regex matches in a string.

index.js
const str = 'one two one one'; let count = 0; const regex = /one/g; while (regex.exec(str) !== null) { count += 1; } console.log(count); // ๐Ÿ‘‰๏ธ 3

The exec() method is very similar to String.match().

It returns null if the match fails, otherwise, it returns an array with the match.

We used a while loop to iterate for as long as the method doesn't return null.

On each iteration, we increment the count variable by 1.

Notice that we used the let keyword when declaring the variable.

Variables declared using const cannot be reassigned.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev