views:

73

answers:

4

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'
+10  A: 
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);
rchern
+1 - absolutely the way to go
Nick Craver
Just make sure you quote the word to search for (`is`, in this case) if it contains any special characters.
Antal S-Z
+1  A: 
function countInstances(string, word) {
   var substrings = string.split(word);
   return substrings.length - 1;
}
Orbit
This is an unsafe/inaccurate approach, for example: `countInstances("isisisisisis") === 0`.
Nick Craver
returns 6 for me...
Orbit
@Nick Craver: That returns six for me too (running Google Chrome on OS X).
Antal S-Z
@Antal - Looks like a bug in the previous beta build of chrome, works after updating to latest, I'd still steer clear of this method though.
Nick Craver
A: 

You can use match to define such function:

String.prototype.count = function(search) {
    return this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g")).length;
}
Gumbo
+1  A: 

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?

Tim