match method lets us find the substrings with the given regex pattern in the string it’s called on.
To use it, we write:
const str = "This is a string."; const count = [...(str.match(/is/g) || )].length; console.log(count);
We have the
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.
count is 2 since there’re 2 instances of
'is' in the string.
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);
'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.
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.