最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Mar 24, 2010 at 14:54 William CallejaWilliam Calleja 4,18511 gold badges43 silver badges51 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 13

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 ment 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 ment 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.

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

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;
}
发布评论

评论列表(0)

  1. 暂无评论