Quantcast
Channel: How to count string occurrence in string? - Stack Overflow
Viewing all articles
Browse latest Browse all 43

Answer by b_rop for How to count string occurrence in string?

$
0
0

The parameters:ustring: the superset stringcountChar: 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'));

Viewing all articles
Browse latest Browse all 43

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>