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'
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'
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(count.length);
function countInstances(string, word) {
   var substrings = string.split(word);
   return substrings.length - 1;
}
You can use match to define such function:
String.prototype.count = function(search) {
    return this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g")).length;
}
It depends on whether you accept overlapping instances, e.g.
var t = "sss";
How many instances of the substring "ss" are in the string above? 1 or 2? Do you leapfrog over each instance, or move the pointer character-by-character, looking for the substring?