views:

97

answers:

3

In Javascript is there a function that returns the number of times that a given string occurs? I need to return a numeric value that is equal to the number of times that a given string occurs within a particular string for instance:

var myString = "This is a test text"

If I had to search for 'te' in the above string it would return 2.

+13  A: 
T.J. Crowder
instead of te can I pass a variable?
William Calleja
@William: Sure, you can build a RegExp from a string: `new RegExp(theString, g)` (https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/RegExp), but you have to escape any special regex characters in the string (this is also true with the literal I supplied, but it's trickier in strings). For instance, to search for `[` you have to specify `\[` in a literal RegExp (`/\[/g`); to do that via a string you have to *further* escape the backslash since you're using it in a string literal, so: `new RegExp("\\[", g)`. You see how that can be more confusing. :-)
T.J. Crowder
thanks a million sir, you're a life saver!
William Calleja
@William: No worries. :-)
T.J. Crowder
while (re.exec(str)) {}This is a lovely method, but it does not avoid creating arrays-it creates a new one each time you execute the loop.the match method you show first is a more efficient way to count pattern matches.
kennebec
@kennebec: Very good point, my explanation was unclear. I meant that it avoided creating one large interim array. I've gone back and fixed that, thanks. :-)
T.J. Crowder
@kennebec: And have now used `test` instead. Doh!
T.J. Crowder
+2  A: 

Here is an implementation of php's substr_count() in js. May this function bring you much joy...

substr_count = function(needle, haystack)
{
 var occurrences = 0;

 for (var i=0; i < haystack.length; i++)
 {
  if (needle == haystack.substr(i, needle.length))
  {
   occurrences++;
  }
 }

 return occurrences; 
}

alert(substr_count('hey', 'hey hey ehy w00lzworth'));
John Himmelman
+1 for the argument names. :-)
T.J. Crowder
+1  A: 

I like to use test to count matches- with a global regular expression it works through a string from each lastIndex, like exec, but does not have to build any arrays:

var c=0;
while(rx.test(string)) c++


String.prototype.count= function(rx){
    if(typeof rx== 'string') rx= RegExp(rx,'g');
    var c= 0;
    while(rx.test(this)) c++;
    return c;
}
kennebec
`RegExp#test` - doh! Big +1
T.J. Crowder