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.