William Calleja
William Calleja

Reputation: 4175

In Javascript is there a function that returns the number of times that a given string occurs?

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.

Upvotes: 3

Views: 1112

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1075885

Very nearly: You can use String#match to do this:

var count = "This is a test text".match(/te/g).length;

That uses the regular expression /te/g (search for "te" literally, globally) and asks the string to return an array of matches. The array's length is then the count.

Naturally that creates an intermediary array, which may not be ideal if you have a large result set. If you don't mind looping:

function countMatches(str, re) {
    var counter;

    counter = 0;
    while (re.test(str)) {
        ++counter;
    }
    return counter;
}

var count = countMatches("This is a test text", /te/g);

That uses RegExp#test to find matches without creating intermediary arrays. (Thanks to kennebec for the comment pointing out that my earlier use of RegExp#exec in the above created intermediary arrays unnecessarily!) Whether it's more efficient will depend entirely on how many of these you expect to match, since the version creating the one big array will probably be optimized within the String#match call and so be faster at the expense of more (temporary) memory use — a large result set may bog down trying to allocate memory, but a small one is unlikely to.

Edit Re your comment below, if you're not looking for patterns and you don't mind looping, you may want to do this instead:

function countMatches(str, substr) {
    var index, counter, sublength;

    sublength = substr.length;
    counter = 0;
    for (index = str.indexOf(substr);
         index >= 0;
         index = str.indexOf(substr, index + sublength))
    {
        ++counter;
    }
    return counter;
}

var count = countMatches("This is a test text", "te");

There's no pre-baked non-RegExp way to do this that I know of.

Upvotes: 13

kennebec
kennebec

Reputation: 104850

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;
}

Upvotes: 2

John Himmelman
John Himmelman

Reputation: 22010

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'));

Upvotes: 2

Related Questions