Count the Number of Regex Matches using JavaScript


Borislav Hadzhiev

Sun Nov 14 20212 min read

Count the Number of Regex Matches #

To count the number of regex matches, call the match() method on the string, passing it the regular expression as a parameter, e.g. (str.match(/[a-z]/g) || []).length. The match method returns an array of the regex matches or null if there are no matches found.

const str = 'one two one one'; const count = (str.match(/one/g) || []).length; console.log(count); // 👉️ 3

The only parameter the String.match method takes is a regular expression.

The forward slashes / / mark the beginning and end of the regular expression. In the example, we search for the substring one.

If you need a regex cheatsheet, check out this one from MDN. It's by far the best one out there.

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 regular are found in the string, the match method returns null.

We handle this scenario, by using the logical OR (||) operator. We don't want to access the length property on a value of null because we'd get an error.

The logical OR (||) operator allows us to return an empty array if the match method returned null.

The operator returns the value to the left if it's truthy, otherwise it returns the value to the right.

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

Here are some examples of commonly used regular expressions.

// ✅ 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.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.