Quantcast
Viewing latest article 14
Browse Latest Browse All 43

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

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 latest article 14
Browse Latest Browse All 43

Trending Articles