In this example, we demonstrate a number of different looping functionalities in javascript
This is a string of words. They are very good words. The best words. Bigly.
While loop to iterate through a string
<script>
var myWords = "This is a string of words. They are very good words. The best words. Bigly.";
function search(){
var el = document.getElementById("srch");
var searchTerm = el.value;
if(searchTerm != null){
searchTerm = searchTerm.trim();
el.value = searchTerm;
if(searchTerm != "")
findWords(searchTerm);
}
}
function findWords(word){
var count=0, currPosition = 0;
var locations = new Array();
currPosition = myWords.indexOf(word);
while(currPosition != -1){
count++;
locations.push(currPosition);
currPosition = myWords.indexOf("words", currPosition+1);
}
var el = document.getElementById("demo");
el.innerHTML = myWords + "<br/>" + "occurred " + count + " times <br/>";
el.innerHTML += "at locations: <br/>" + locations.join("<br/>");
}
</script>