Javascript String count substring

Description

Javascript String count substring

let myString = "java2s.com this is a test " + 
               "java2s.com this is a test " + 
               "java2s.com this is a test ";

let foundAtPosition = 0;
let wroxCount = 0;

while (foundAtPosition != -1) {
    foundAtPosition = myString.indexOf("demo", foundAtPosition);

    if (foundAtPosition != -1) {
        wroxCount++;/*www . jav  a 2 s  .c  o  m*/
        foundAtPosition++;
    }
}

console.log("There are " + wroxCount + " occurrences of the word Wrox");



PreviousNext

Related