What’s up programmer, okay? Let’s learn something new!
Watch this content on YouTube:
Identifying the position of a word is very important in programming
Because sometimes we need to know if the phrase contains that word
Or where in the string the word is
Let’s see it in practice:
const frase = "O rato roeu a roupa do rei de Roma"; console.log(frase.indexOf("rei")); // 23 console.log(frase.indexOf("teste")); // -1
I ran two tests on the sentence string, the first one with a word that exists and the second with one a word that doesn’t
n the first console.log we received as a response the number 23, which is the position of the word “rei” in the sentence
That is, “rei” starts at character 23 of the string
So if we get a value greater than 0, we know the word exists in the sentence
And in the second test we received -1, because that word doesn’t exist
So we can conclude that when a word doesn’t exist in a string and we use the indexOf method to check that, we will always get the -1 return
From that point we can run checklists to verify if the word exists or not
Or manipulate the string applying a slice method, if we find the word we’re looking for.
In this article we learned a way to find a word in a string running the indexOf method.
If we get a response greater than 0 from the method, the word exists
And if it’s -1 as a return it means the word doesn’t exist