HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to count string occurrence in string?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringhowcountoccurrence

Problem

How can I count the number of times a particular string occurs in another string. For example, this is what I am trying to do in Javascript:

var temp = "This is a string.";
alert(temp.count("is")); //should output '2'

Solution

The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is twice:



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




And, if there are no matches, it returns 0:



var temp = "Hello World!";
var count = (temp.match(/is/g) || []).length;
console.log(count);

Context

Stack Overflow Q#4009756, score: 1426

Revisions (0)

No revisions yet.