JavaScript String Type

Search

We can search for a pattern within a string by using the indexOf method. This method returns the starting index of pattern within the string. If the pattern is not found -1 is returned.

const chaos = `
Chaos needs no allies,
for it dwells like a poison in every one of us.
`
const poisonStartingIndex = chaos.indexOf("poison")
const greedStartingIndex = chaos.indexOf("greed")
console.log(poisonStartingIndex) // 49
console.log(greedStartingIndex) // -1

Read more on MDN

String.prototype.indexOf()