Is there a function in Javascript that returns the number of times a given string has?

Is there a function in Javascript that returns the number of times a given string has? I need to return a numeric value equal to the number of times a given string occurs on a specific string, for example:

var myString = "This is a test text"

If I had to search for " te" in the above line, it would return 2.

+3
source share
3 answers

Absolutely: You can use String#matchto do this:

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

/te/g ( "" , ) . - .

, , , . :

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

RegExp#test . ( kennebec , , RegExp#exec !) , , , , , String#match , , () β€” , , .

, , , :

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

, RegExp, .

+13

php substr_count() js. ...

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

I like to use the test for counting matches - with a global regular expression, it works through a line from each lastIndex, for example, exec, but does not need to create 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;
}
+2
source

Source: https://habr.com/ru/post/1738344/


All Articles