765

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'
TruMan1
  • 30,176
  • 50
  • 162
  • 301
  • 22
    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 Oct 24 '10 at 19:30
  • 4
    An improved benchmark for this question's answers: http://jsperf.com/string-ocurrence-split-vs-match/2 (based of Kazzkiq's benchmark). – idmean May 27 '15 at 15:08
  • Count Total Amount Of Specific Word In a String JavaScript https://stackoverflow.com/a/65036248/4752258 – Farbod Aprin Nov 29 '20 at 18:57
  • this video seems vaguely related here - "Google Coding Interview With A Facebook Software Engineer" - https://www.youtube.com/watch?v=PIeiiceWe_w – Deryck Dec 13 '20 at 09:07

38 Answers38

1276

The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is twice:

var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);

And, if there are no matches, it returns 0:

var temp = "Hello World!";
var count = (temp.match(/is/g) || []).length;
console.log(count);
Govind Rai
  • 12,166
  • 9
  • 63
  • 80
Rebecca Chernoff
  • 21,115
  • 5
  • 41
  • 45
  • 1
    Just make sure you quote the word to search for (`is`, in this case) if it contains any special characters. – Antal Spector-Zabusky Oct 24 '10 at 20:18
  • 4
    modern and elegant, but Vitimtk's solution is much more efficient. what do you all think of his code? – TruMan1 Nov 04 '11 at 02:15
  • 5
    This answers the question best. If someone asked "How can I do this 10x faster in special case (without regexps)" Vitimtk would win that question. – Dzhaughn Mar 16 '12 at 09:52
  • Will this code work for `temp="What was my string"`? There is no "is" in my search string. – Sri Reddy Jul 05 '12 at 20:51
  • Nope. You need to have `is` in it to match it. – Devner Jul 21 '12 at 13:22
  • 129
    Thanks for this.. I went with `count = (str.match(/is/g) || []).length` to handle if you don't have a match. – Matt Oct 29 '12 at 12:19
  • 11
    I don't think this answer match properly the question, because it doesn't take a string as argument to match, as the use case describe. Sure, you can create dynamically the regexp using `RegExp` constructor and passing the string you're looking for, but in that case you have to escape all the metacharacters. In that scenario, a pure string approach is preferable. – ZER0 Apr 09 '13 at 01:47
  • How can I just extract part of matched pattern. Eg. Instead of is, I use /\s*([a-z]*)\s*/ and only want the part that matches [a-z]. Putting brackets around it does not help. – vivek.m Jul 03 '13 at 06:50
  • I am using `(cached=str.match(/is/g))?cached.length:0` – test30 Oct 09 '13 at 14:52
  • 3
    Matt's answer should be in the answer! – Senči Nov 13 '13 at 15:20
  • 1
    I want to count comma, but it produces error if no comma found – alamnaryab Aug 20 '14 at 15:25
  • Hey, noob here, can anyone tell me what does the code after || part does, i mean why [] ? – penta Jan 05 '17 at 08:46
  • 1
    Try this, to concatenate regex literals: function countStringOccurrences(input, key){ var reg = new RegExp("\\" + key, "g"); var count = (input.match(reg) || []).length; return count; } – Damico Jan 27 '17 at 22:10
  • it is not working if the target string contains any special character – Vikas Bansal May 16 '17 at 12:13
  • 3
    Save Regex for heavy ones, here is a simple one - `alert(temp.split("is").length - 1);` – Anand Rockzz Aug 10 '18 at 02:07
  • `|| [ ]` returns `[ ]` (empty array) if match didnt find anything (it returns null then, and in a `null or []` result is the latter) @Kosem @penta – n-smits Jun 16 '20 at 15:56
  • Count Total Amount Of Specific Word In a String JavaScript https://stackoverflow.com/a/65036248/4752258 – Farbod Aprin Nov 29 '20 at 18:57
  • This answer is completely wrong. If my match is an opening square bracket, then it will interpret it as a opening character class. This will make it throw an error. `String#match` is made for regular expressions, not strings. – Hemant Mar 29 '21 at 18:35
  • Since ES2020, there is a shorten and more readable way to do it by combining Optional chaining and Nullish coalescing operator `const count = temp.match(/is/g)?.length ?? 0;` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator – Milton Castro Jun 16 '21 at 18:25
271
/** Function that count occurrences of a substring in a string;
 * @param {String} string               The string
 * @param {String} subString            The sub string to search for
 * @param {Boolean} [allowOverlapping]  Optional. (Default:false)
 *
 * @author Vitim.us https://gist.github.com/victornpb/7736865
 * @see Unit Test https://jsfiddle.net/Victornpb/5axuh96u/
 * @see https://stackoverflow.com/a/7924240/938822
 */
function occurrences(string, subString, allowOverlapping) {

    string += "";
    subString += "";
    if (subString.length <= 0) return (string.length + 1);

    var n = 0,
        pos = 0,
        step = allowOverlapping ? 1 : subString.length;

    while (true) {
        pos = string.indexOf(subString, pos);
        if (pos >= 0) {
            ++n;
            pos += step;
        } else break;
    }
    return n;
}

Usage

occurrences("foofoofoo", "bar"); //0

occurrences("foofoofoo", "foo"); //3

occurrences("foofoofoo", "foofoo"); //1

allowOverlapping

occurrences("foofoofoo", "foofoo", true); //2

Matches:

  foofoofoo
1 `----´
2    `----´

Unit Test

Benchmark

I've made a benchmark test and my function is more then 10 times faster then the regexp match function posted by gumbo. In my test string is 25 chars length. with 2 occurences of the character 'o'. I executed 1 000 000 times in Safari.

Safari 5.1

Benchmark> Total time execution: 5617 ms (regexp)

Benchmark> Total time execution: 881 ms (my function 6.4x faster)

Firefox 4

Benchmark> Total time execution: 8547 ms (Rexexp)

Benchmark> Total time execution: 634 ms (my function 13.5x faster)


Edit: changes I've made

  • cached substring length

  • added type-casting to string.

  • added optional 'allowOverlapping' parameter

  • fixed correct output for "" empty substring case.

Gist

Vitim.us
  • 18,445
  • 15
  • 88
  • 102
  • 6
    I repeated this test in Safari 5 and got similar results with a small (100b) string, but with a larger string (16kb), the regex ran faster for me. For one iteration (not 1,000,000), the difference was less than a millisecond anyway, so my vote goes to the regex. – arlomedia Apr 04 '12 at 23:04
  • 1
    @ajax333221 OMG you read my mind, I did this improvement a few days ago, and I was going to edit my answer http://jsperf.com/count-string-occurrence-in-string – Vitim.us Jun 07 '12 at 03:24
  • I don't understand this line: if(subString.length<=0) return string.length+1; If no search string is supplied, I'd return 0. Otherwise this is a nice useful script. – Rayfleck Jun 09 '12 at 15:57
  • @Rayfleck this is to prevent infinity loop when entering `occurrence('foo','')` will return 4, because `occurrences('','')==1` so `occurrence(bar,'')===bar.lenght+1` this is the same behavior of regex – Vitim.us Jun 11 '12 at 02:55
  • 1
    nice. total control and clear. Maybe I'm an old dog, but "old school" when it works isn't a bad thing! – bladnman Aug 13 '12 at 20:37
  • 5
    I found your code in use here: http://www.success-equation.com/mind_reader.html . Really nice the programmer minded putting a reference there. – Bruno Kim Oct 09 '12 at 02:57
  • @Vitim.us What is the purpose of the allowOverlapping param ? – cssyphus Jun 15 '13 at 16:52
  • 1
    `occurrences("aaa", "aa") == 1` and `occurrences("aaa", "aa", true) == 2` – Vitim.us Jun 16 '13 at 22:47
  • 1
    @Vitim.us it shouldn't be even faster if You use pre-increment instead of post-increment? In while loop for n variable. – MNie Oct 02 '14 at 08:43
  • Anyone know what the purpose of string += "", and subString += ""? Seems trivial, but it doesn't seem like it is doing anything. – Dan Zuzevich Jun 07 '17 at 13:01
  • 3
    @DanielZuzevich it will coerce the types to *String*, in case you do `occurrences(11,1) //2` and it would still work. (It is faster doing this way instead of checking for types and calling *toString()*) – Vitim.us Jun 07 '17 at 18:52
  • According to my test in modern browsers, split appears to be fastest, especially for large strings (which is surprising to me). (Tested on Firefox 56 and 58, Chrome 63, IE 11; run 3,000,000 times for a string with 580 chars.) – Danny Lin Dec 14 '17 at 16:39
  • http://jsperf.com/count-string-occurrence-in-string creates a regex on every call. If you create the regex only once, it's almost as fast in Firefox, and *faster* with regex in Chrome. – unhammer Jan 24 '18 at 13:23
  • 1
    It’s not always one needs scripts that are fast, but today, I need it and this helped me. I’m parsing a list of 79850 words to create a probability map for each letter to be followed by each other, in different languages. It’s needless to say that speed is important for that one, since I’m doing 26*26*79850 loops, with a match test each time. – le hollandais volant Aug 21 '18 at 16:26
  • Someone will be shocked after trying `text.split('foo').length` – StefansArya Feb 09 '19 at 12:11
  • When can it be the case that subString.length < 0 ? and why not subString.length == 0 enough – user3808307 Oct 10 '20 at 04:05
179

function countInstances(string, word) {
   return string.split(word).length - 1;
}
console.log(countInstances("This is a string", "is"))
аlex dykyі
  • 4,877
  • 25
  • 38
Brandon Frohbieter
  • 16,827
  • 3
  • 36
  • 61
105

You can try this:

var theString = "This is a string.";
console.log(theString.split("is").length - 1);
Ruslan López
  • 4,289
  • 1
  • 25
  • 36
Freezy Ize
  • 1,111
  • 2
  • 9
  • 11
35

My solution:

var temp = "This is a string.";

function countOcurrences(str, value) {
  var regExp = new RegExp(value, "gi");
  return (str.match(regExp) || []).length;
}

console.log(countOcurrences(temp, 'is'));
Ruslan López
  • 4,289
  • 1
  • 25
  • 36
Gere
  • 2,014
  • 23
  • 23
  • 5
    maybe it would be better to return (str.match(regExp) || []).length; That way you don't evaluate the regular expression twice? – aikeru Dec 07 '13 at 04:08
  • 4
    you also need to scape your string or `countOcurrences('Hello...','.')==8` and not 3 – Vitim.us May 09 '14 at 03:16
20

You can use match to define such function:

String.prototype.count = function(search) {
    var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
    return m ? m.length:0;
}
webXL
  • 1,600
  • 1
  • 13
  • 21
Gumbo
  • 620,600
  • 104
  • 758
  • 828
13

The non-regex version:

 var string = 'This is a string',
    searchFor = 'is',
    count = 0,
    pos = string.indexOf(searchFor);

while (pos > -1) {
    ++count;
    pos = string.indexOf(searchFor, ++pos);
}

console.log(count);   // 2
Faraz Kelhini
  • 3,797
  • 31
  • 38
  • 1. It's only for single char search, too subtle 2. even OP asks for `is` occurences – vladkras May 20 '16 at 05:57
  • 2
    This is probably the fastest implementation here, but it would be even faster if you replaced "++pos" with "pos+=searchFor.length" – hanshenrik Apr 01 '19 at 13:43
13

Just code-golfing Rebecca Chernoff's solution :-)

alert(("This is a string.".match(/is/g) || []).length);
Andrew Myers
  • 2,676
  • 5
  • 30
  • 39
Tomas
  • 54,903
  • 47
  • 225
  • 361
11

String.prototype.Count = function (find) {
    return this.split(find).length - 1;
}

console.log("This is a string.".Count("is"));

This will return 2.

Sunil Garg
  • 12,670
  • 19
  • 110
  • 153
Fad Seck
  • 111
  • 1
  • 2
8

Here is the fastest function!

Why is it faster?

  • Doesn't check char by char (with 1 exception)
  • Uses a while and increments 1 var (the char count var) vs. a for loop checking the length and incrementing 2 vars (usually var i and a var with the char count)
  • Uses WAY less vars
  • Doesn't use regex!
  • Uses an (hopefully) highly optimized function
  • All operations are as combined as they can be, avoiding slowdowns due to multiple operations

    String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};
    

Here is a slower and more readable version:

    String.prototype.timesCharExist = function ( chr ) {
        var total = 0, last_location = 0, single_char = ( chr + '' )[0];
        while( last_location = this.indexOf( single_char, last_location ) + 1 )
        {
            total = total + 1;
        }
        return total;
    };

This one is slower because of the counter, long var names and misuse of 1 var.

To use it, you simply do this:

    'The char "a" only shows up twice'.timesCharExist('a');

Edit: (2013/12/16)

DON'T use with Opera 12.16 or older! it will take almost 2.5x more than the regex solution!

On chrome, this solution will take between 14ms and 20ms for 1,000,000 characters.

The regex solution takes 11-14ms for the same amount.

Using a function (outside String.prototype) will take about 10-13ms.

Here is the code used:

    String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};

    var x=Array(100001).join('1234567890');

    console.time('proto');x.timesCharExist('1');console.timeEnd('proto');

    console.time('regex');x.match(/1/g).length;console.timeEnd('regex');

    var timesCharExist=function(x,c){var t=0,l=0,c=(c+'')[0];while(l=x.indexOf(c,l)+1)++t;return t;};

    console.time('func');timesCharExist(x,'1');console.timeEnd('func');

The result of all the solutions should be 100,000!

Note: if you want this function to count more than 1 char, change where is c=(c+'')[0] into c=c+''

Ismael Miguel
  • 4,031
  • 1
  • 30
  • 37
  • 1
    the prototype was AN EXAMPLE! You can use the function as you please! You can even do this: var timesFunctionExist=function(x,c){var t=0,l=0,c=(c+'')[0];while(l=x.indexOf(c,l)+1)++t;return t}); alert(timesCharExist('The char "a" only shows up twice','a'));! (this will speed up a little more cause i wont be messing with prototypes). If you think I'm wrong, why don't you show it before throwing rocks at me? Prove to me that my function sucks and i will accept it. Show me a test case. And the length of vars does have influence on speed. You can test it. – Ismael Miguel Oct 08 '13 at 11:02
7

var temp = "This is a string.";
console.log((temp.match(new RegExp("is", "g")) || []).length);
Ruslan López
  • 4,289
  • 1
  • 25
  • 36
Sunil Garg
  • 12,670
  • 19
  • 110
  • 153
4

I think the purpose for regex is much different from indexOf. indexOf simply find the occurance of a certain string while in regex you can use wildcards like [A-Z] which means it will find any capital character in the word without stating the actual character.

Example:

 var index = "This is a string".indexOf("is");
 console.log(index);
 var length = "This is a string".match(/[a-z]/g).length;
 // where [a-z] is a regex wildcard expression thats why its slower
 console.log(length);
Ruslan López
  • 4,289
  • 1
  • 25
  • 36
Simm
  • 41
  • 2
4

A simple way would be to split the string on the required word, the word for which we want to calculate the number of occurences, and subtract 1 from the number of parts:

function checkOccurences(string, word) {
      return string.split(word).length - 1;
}
const text="Let us see. see above, see below, see forward, see backward, see left, see right until we will be right"; 
const count=countOccurences(text,"see "); // 2
H S Progr
  • 4,779
  • 2
  • 22
  • 31
3

Super duper old, but I needed to do something like this today and only thought to check SO afterwards. Works pretty fast for me.

String.prototype.count = function(substr,start,overlap) {
    overlap = overlap || false;
    start = start || 0;

    var count = 0, 
        offset = overlap ? 1 : substr.length;

    while((start = this.indexOf(substr, start) + offset) !== (offset - 1))
        ++count;
    return count;
};
Jason Larke
  • 4,959
  • 23
  • 28
3
       var myString = "This is a string.";
        var foundAtPosition = 0;
        var Count = 0;
        while (foundAtPosition != -1)
        {
            foundAtPosition = myString.indexOf("is",foundAtPosition);
            if (foundAtPosition != -1)
            {
                Count++;
                foundAtPosition++;
            }
        }
        document.write("There are " + Count + " occurrences of the word IS");

Refer :- count a substring appears in the string for step by step explanation.

Roney Michael
  • 3,914
  • 4
  • 28
  • 45
Ranju
  • 31
  • 2
3

For anyone that finds this thread in the future, note that the accepted answer will not always return the correct value if you generalize it, since it will choke on regex operators like $ and .. Here's a better version, that can handle any needle:

function occurrences (haystack, needle) {
  var _needle = needle
    .replace(/\[/g, '\\[')
    .replace(/\]/g, '\\]')
  return (
    haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
  ).length
}
bcherny
  • 2,884
  • 1
  • 23
  • 32
3

Building upon @Vittim.us answer above. I like the control his method gives me, making it easy to extend, but I needed to add case insensitivity and limit matches to whole words with support for punctuation. (e.g. "bath" is in "take a bath." but not "bathing")

The punctuation regex came from: https://stackoverflow.com/a/25575009/497745 (How can I strip all punctuation from a string in JavaScript using regex?)

function keywordOccurrences(string, subString, allowOverlapping, caseInsensitive, wholeWord)
{

    string += "";
    subString += "";
    if (subString.length <= 0) return (string.length + 1); //deal with empty strings

    if(caseInsensitive)
    {            
        string = string.toLowerCase();
        subString = subString.toLowerCase();
    }

    var n = 0,
        pos = 0,
        step = allowOverlapping ? 1 : subString.length,
        stringLength = string.length,
        subStringLength = subString.length;

    while (true)
    {
        pos = string.indexOf(subString, pos);
        if (pos >= 0)
        {
            var matchPos = pos;
            pos += step; //slide forward the position pointer no matter what

            if(wholeWord) //only whole word matches are desired
            {
                if(matchPos > 0) //if the string is not at the very beginning we need to check if the previous character is whitespace
                {                        
                    if(!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?@\[\]^_`{|}~]/.test(string[matchPos - 1])) //ignore punctuation
                    {
                        continue; //then this is not a match
                    }
                }

                var matchEnd = matchPos + subStringLength;
                if(matchEnd < stringLength - 1)
                {                        
                    if (!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?@\[\]^_`{|}~]/.test(string[matchEnd])) //ignore punctuation
                    {
                        continue; //then this is not a match
                    }
                }
            }

            ++n;                
        } else break;
    }
    return n;
}

Please feel free to modify and refactor this answer if you spot bugs or improvements.

Community
  • 1
  • 1
Ayo I
  • 7,212
  • 4
  • 27
  • 39
2

Try it

<?php 
$str = "33,33,56,89,56,56";
echo substr_count($str, '56');
?>

<script type="text/javascript">
var temp = "33,33,56,89,56,56";
var count = temp.match(/56/g);  
alert(count.length);
</script>
2

Simple version without regex:

var temp = "This is a string.";

var count = (temp.split('is').length - 1);

alert(count);
Jorge Alberto
  • 117
  • 1
  • 5
2

No one will ever see this, but it's good to bring back recursion and arrow functions once in a while (pun gloriously intended)

String.prototype.occurrencesOf = function(s, i) {
 return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};
BaseZen
  • 8,494
  • 2
  • 34
  • 47
2

ES2020 offers a new MatchAll which might be of use in this particular context.

Here we create a new RegExp, please ensure you pass 'g' into the function.

Convert the result using Array.from and count the length, which returns 2 as per the original requestor's desired output.

let strToCheck = RegExp('is', 'g')
let matchesReg = "This is a string.".matchAll(strToCheck)
console.log(Array.from(matchesReg).length) // 2
dimButTries
  • 446
  • 3
  • 11
1

Now this is a very old thread i've come across but as many have pushed their answer's, here is mine in a hope to help someone with this simple code.

var search_value = "This is a dummy sentence!";
var letter = 'a'; /*Can take any letter, have put in a var if anyone wants to use this variable dynamically*/
letter = letter && "string" === typeof letter ? letter : "";
var count;
for (var i = count = 0; i < search_value.length; count += (search_value[i++] == letter));
console.log(count);

I'm not sure if it is the fastest solution but i preferred it for simplicity and for not using regex (i just don't like using them!)

Tushar Shukla
  • 4,308
  • 2
  • 26
  • 37
1
 function substrCount( str, x ) {
   let count = -1, pos = 0;
   do {
     pos = str.indexOf( x, pos ) + 1;
     count++;
   } while( pos > 0 );
   return count;
 }
mendezcode
  • 757
  • 7
  • 7
1

You could try this

let count = s.length - s.replace(/is/g, "").length;
fahrenheit317
  • 11
  • 1
  • 3
1

We can use the js split function, and it's length minus 1 will be the number of occurrences.

var temp = "This is a string.";
alert(temp.split('is').length-1);
SherylHohman
  • 14,460
  • 16
  • 79
  • 88
  • 1
    Welcome. SO works differently than forums. SO is designed such that good answers should be upvoted, not duplicated. The answer you have suggested already exists, so you should upvote it instead. There are also answers using the same concept at its base, but also consider a more nuanced interpretation (eg, should `ss` in `sss` count as `1` or `2`? ). So maybe upvote those as well, if you like. For onboarding, please read up on "how to answer" & "how to ask" topics in the help section, linked to at the top of every page. We appreciate & look forward to your future contributions. – SherylHohman Feb 21 '22 at 14:01
  • That said, great on posting in a concise, clear manner, with an attempt to provide an explanation, which many of the oldest answers failed to do. To be clear, their code-only answers are discouraged on SO (though it wasn't always well enforced back then). Looking forward to seeing more in the future. – SherylHohman Feb 21 '22 at 14:47
1

Here is my solution, in 2022, using map() and filter() :

string = "Xanthous: A person with yellow hair. Her hair was very xanthous in colour."       
count = string.split('').map((e,i) => { if(e === 'e') return i;}).filter(Boolean).length

Just for the fun of using these functions. The example counts the number of "e" in my string.

This is the same as using the match() function :

(string.match(/e/g)||[]).length

or simply the split() function:

string.split('e').length - 1

I think the best is to use match(), because it consumes less resources! My answer is just for fun and to show that there are many possibilities to solve this problem

Elell
  • 11
  • 2
0

var countInstances = function(body, target) {
  var globalcounter = 0;
  var concatstring  = '';
  for(var i=0,j=target.length;i<body.length;i++){
    concatstring = body.substring(i-1,j);
    
    if(concatstring === target){
       globalcounter += 1;
       concatstring = '';
    }
  }
  
  
  return globalcounter;
 
};

console.log(   countInstances('abcabc', 'abc')   ); // ==> 2
console.log(   countInstances('ababa', 'aba')   ); // ==> 2
console.log(   countInstances('aaabbb', 'ab')   ); // ==> 1
Kamal
  • 2,450
  • 1
  • 7
  • 13
0

substr_count translated to Javascript from php


function substr_count (haystack, needle, offset, length) { 
  // eslint-disable-line camelcase
  //  discuss at: https://locutus.io/php/substr_count/
  // original by: Kevin van Zonneveld (https://kvz.io)
  // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
  // improved by: Brett Zamir (https://brett-zamir.me)
  // improved by: Thomas
  //   example 1: substr_count('Kevin van Zonneveld', 'e')
  //   returns 1: 3
  //   example 2: substr_count('Kevin van Zonneveld', 'K', 1)
  //   returns 2: 0
  //   example 3: substr_count('Kevin van Zonneveld', 'Z', 0, 10)
  //   returns 3: false

  var cnt = 0

  haystack += ''
  needle += ''
  if (isNaN(offset)) {
    offset = 0
  }
  if (isNaN(length)) {
    length = 0
  }
  if (needle.length === 0) {
    return false
  }
  offset--

  while ((offset = haystack.indexOf(needle, offset + 1)) !== -1) {
    if (length > 0 && (offset + needle.length) > length) {
      return false
    }
    cnt++
  }

  return cnt
}

Check out Locutus's Translation Of Php's substr_count function

0

The parameters: ustring: the superset string countChar: the substring

A function to count substring occurrence in JavaScript:

function subStringCount(ustring, countChar){
  var correspCount = 0;
  var corresp = false;
  var amount = 0;
  var prevChar = null;
  
 for(var i=0; i!=ustring.length; i++){

     if(ustring.charAt(i) == countChar.charAt(0) && corresp == false){
       corresp = true;
       correspCount += 1;
       if(correspCount == countChar.length){
         amount+=1;
         corresp = false;
         correspCount = 0;
       }
       prevChar = 1;
     }
     else if(ustring.charAt(i) == countChar.charAt(prevChar) && corresp == true){
       correspCount += 1;
       if(correspCount == countChar.length){
         amount+=1;
         corresp = false;
         correspCount = 0;
         prevChar = null;
       }else{
         prevChar += 1 ;
       }
     }else{
       corresp = false;
       correspCount = 0;
     }
 } 
 return amount;
}

console.log(subStringCount('Hello World, Hello World', 'll'));
b_rop
  • 1
  • 1
0

var str = 'stackoverflow';
var arr = Array.from(str);
console.log(arr);

for (let a = 0; a <= arr.length; a++) {
  var temp = arr[a];
  var c = 0;
  for (let b = 0; b <= arr.length; b++) {
    if (temp === arr[b]) {
      c++;
    }

  }
  console.log(`the ${arr[a]} is counted for ${c}`)
}
  • Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes – Ran Marciano Dec 13 '20 at 09:23
0

Iterate less the second time (just when first letter of substring matches) but still uses 2 for loops:

   function findSubstringOccurrences(str, word) {
        let occurrences = 0;
        for(let i=0; i<str.length; i++){
            if(word[0] === str[i]){ // to make it faster and iterate less
                for(let j=0; j<word.length; j++){
                    if(str[i+j] !== word[j]) break;
                    if(j === word.length - 1) occurrences++;
                }
            }
        }
        return occurrences;
    }
    
    console.log(findSubstringOccurrences("jdlfkfomgkdjfomglo", "omg"));
Michel
  • 27
  • 3
0
//Try this code

const countSubStr = (str, search) => {
    let arrStr = str.split('');
    let i = 0, count = 0;

    while(i < arrStr.length){
        let subStr = i + search.length + 1 <= arrStr.length ?
                  arrStr.slice(i, i+search.length).join('') :
                  arrStr.slice(i).join('');
        if(subStr === search){
            count++;
            arrStr.splice(i, search.length);
        }else{
            i++;
        }
    }
    return count;
  }
Force Bolt
  • 883
  • 7
  • 7
0
var mystring = 'This is the lorel ipsum text';
var mycharArray = mystring.split('');
var opArr = [];
for(let i=0;i<mycharArray.length;i++){
if(mycharArray[i]=='i'){//match the character you want to match
    opArr.push(i);
  }}
console.log(opArr); // it will return matching index position
console.log(opArr.length); // it will return length
Sagar Shinde
  • 142
  • 9
0
const getLetterMatchCount = (guessedWord, secretWord) => {
  const secretLetters = secretWord.split('');
  const guessedLetterSet = new Set(guessedWord);
  return secretLetters.filter(letter => guessedLetterSet.has(letter)).length;
};
const str = "rahul";
const str1 = "rajendra";

getLetterMatchCount(str, str1)
  • With so many other answers, it would be good if you added some explanation as to how your code works and what advantages it has over other proposed solutions. – Adrian Mole Aug 24 '21 at 12:01
0

This function works in three modes: looking for the frequency of a single character within a string , a contiguous substring within a string then if it does match one it moves right ahead to next one right after it , and the third is similar to the previous one except it it will also count intersecting substrings within the given string

function substringFrequency(string , substring , conjunction){
    let index 
    let occurenceFrequency  = 0
    for (let i=0 ; i < string.length  ; i++){
        index = string.indexOf(substring , i)
        if (index != -1){
            if ((substring.length == 1 ) || conjunction == true) {
                i = index 
            }else {
                i = index + 1
            }
            occurenceFrequency++
        }else{
            break
        } 
    }
    return (occurenceFrequency)
}

console.log(substringFrequency('vvvv' , 'v' ))
console.log(substringFrequency('vvvv' , 'vv'))
console.log(substringFrequency('vvvv' , 'vv' , true))
polendina
  • 69
  • 2
  • 10
  • @Calculuswhiz got it more integrated with the for loop code block – polendina Dec 08 '21 at 23:12
  • @Calculuswhiz initially my first edit was due to your comment to solely integrate the variable i within the for loop body , still during so i've noticed that intersecting substrings gets omitted , and that only separate substrings are counted . so i defaulted to count separate ones as it made more sense , yet as the original question didn't explicitly specify any and i don't want to impose any behavior in order to accommodate varying use cases ,i appended more statements . – polendina Dec 09 '21 at 00:27
-1

Answer for Leandro Batista : just a problem with the regex expression.

 "use strict";
 var dataFromDB = "testal";
 
  $('input[name="tbInput"]').on("change",function(){
 var charToTest = $(this).val();
 var howManyChars = charToTest.length;
 var nrMatches = 0;
 if(howManyChars !== 0){
  charToTest = charToTest.charAt(0);
  var regexp = new RegExp(charToTest,'gi');
  var arrMatches = dataFromDB.match(regexp);
  nrMatches = arrMatches ? arrMatches.length : 0;
 }
  $('#result').html(nrMatches.toString());

  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
What do you wanna count <input type="text" name="tbInput" value=""><br />
Number of occurences = <span id="result">0</span>
</div>
PhilMaGeo
  • 541
  • 6
  • 8
-1

came across this post.

let str = 'As sly as a fox, as strong as an ox';

let target = 'as'; // let's look for it

let pos = 0;
while (true) {
  let foundPos = str.indexOf(target, pos);
  if (foundPos == -1) break;

  alert( `Found at ${foundPos}` );
  pos = foundPos + 1; // continue the search from the next position
}

The same algorithm can be layed out shorter:

let str = "As sly as a fox, as strong as an ox";
let target = "as";

let pos = -1;
while ((pos = str.indexOf(target, pos + 1)) != -1) {
  alert( pos );
}
Ashok R
  • 18,378
  • 8
  • 66
  • 67
-2

Try this:

function countString(str, search){
    var count=0;
    var index=str.indexOf(search);
    while(index!=-1){
        count++;
        index=str.indexOf(search,index+1);
    }
    return count;
}
Diogo Arenhart
  • 287
  • 3
  • 6
  • 15