Sometimes, we want to get how many times a character occurs in a string with JavaScript.
In this article, we’ll look at how to get how many times a character occurs in a string with JavaScript.
How to get how many times a character occurs in a string with JavaScript?
To get how many times a character occurs in a string with JavaScript, we can use the string match method.
For instance, we write
const string = "aajlkjjskdjfAlsjfghgfjjgfkk";
console.log(string.match(/a/gi).length)
to call string.match with a regex that matches all instances of 'a' in a case insensitive manner.
match returns an array of matches, so we can use the length property to get the count of the matches.
Conclusion
To get how many times a character occurs in a string with JavaScript, we can use the string match method.