jQuery
JavaScript: Count Occurrences Of String In String Examples
At some point or the other, it might be useful to count the number of occurrences of a specific word or a string in another string using JavaScript. In this article, I am going to share very easy example to do just that with the help of easy to follow examples. Read on to find out more.
How To Count Occurrences In String Using JavaScript
Let’s look at how to do this with an example. Consider that we have a string that says: “This is a string.”. Now we want to find out the number of times the word “is” has repeated in that string. So here’s how it can be done in the most simplest way:
Example:
<p>The string that needs to be searched in is: <strong>"This is a string."</strong>. So this is our Haystack.</p> <p>We want to search fo the word <strong>"is"</strong>. So this is our Needle.</p> <p>You should see an alert as soon as the page loads.</p> <script type="text/javascript"> var temp = "This is a string."; // the g in the regular expression says to search the whole string // rather than just find the first occurrence var count = temp.match(/is/g); alert('The word "is" is repeated ' + count.length + ' times.'); </script>
Simple, isn’t it?
Do you know of any other ways to count the number of times a string or a word is repeated in another string using JavaScript? Feel free to suggest by commenting below.