Categories
JavaScript Answers

How to Count the Number of Substring Occurrences in a JavaScript String?

Spread the love

Sometimes, we’ve to count the number of occurrences of a substring in our JavaScript strings.

In this article, we’ll look at how to count the number of substring occurrences in a JavaScript string.

String.prototype.match

The string match method lets us find the substrings with the given regex pattern in the string it’s called on.

Therefore, we can use it to find the number of substring occurrences in a JavaScript string.

To use it, we write:

const str = "This is a string.";
const count = [...(str.match(/is/g) || [])].length;
console.log(count);

We have the str string.

And we call match on it with the substring we’re looking for and the g flag to look for all instances of the substring in the string.

If there’re no matches, it returns undefined , so we’ve to add || [] to return an empty array in that case.

Then we get the length of the array to get the number of occurences.

So count is 2 since there’re 2 instances of 'is' in the string.

String.prototype.split

We can use the split method to split a string by its separator.

So we can use split to split the string by the substring we’re looking for and subtract that by 1 to get the number of instances of a substring.

To do this, we write:

const str = "This is a string.";
const count = str.split('is').length - 1;
console.log(count);

We call split with 'is' to split the str string with'is' as the separator.

Then we’ve to minus 1 from the returned length to get the right result.

Conclusion

To count the number of instances of a substring in a string, we can either split the string or search for it using a regex.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *