IndexOf

Page section: posts

The indexOf() finds the position of the first character in a string that is in a longer string. For instance it might be looking for the phrase “shoe shine” in a web page. If it occurs more than once it finds the position only of the first instance. lastIndexOf() can find the position the last instance of the same string.

If the string does not exist within the larger string being search (ie. if shoeshine is not on the web page) a value of -1 is returned.

What use is it?

It can be used with slice() to search and replace a word.

Examples

let textToCheck = "How many donkeys are there in barbados?";
if (textToCheck.indexOf("donkey") !== -1) {
    alert("There is a donkey in here");
}

Here is a simple check to see if a word exists in the sentence:

The basking shark is knitting on the lawn.

The code for this is:

function checkWord() {
    let word = prompt("type a word to search for");
    if (moreText.indexOf(word) !== -1) {
      alert("The word you are looking for is here at position " + moreText.indexOf(word) + ". " + word + " contains " + word.length + " letters.");
    }
    //   alert("contains " + word.length);
    else {
        alert("Sorry we don't have that word in the sentence right now.");
    }
}

Using replace()

You can use replace() to change one string for another:

let theWay = "This way is home";

theWay.replace("home", "trouble");