In this article we will learn how to search for word in strings, actually any type of text, identifying whether it is present or not.
Hey you programmer, okay? Let’s learn something new!
We use native language methods to achieve our result, let’s see it:
let frase = 'Será que existe João nesta frase?'; console.log(frase.indexOf("João")); // 16 console.log(frase.indexOf("Pedro")); // -1
To search for words or text, let’s use the indexOf() method.
Using the text to be found as a parameter
We will receive two types of returns:
- Any number other than -1: The word has been found, and this number represents the index of its first letter in the text;
- -1: When we receive this value, the word does not exist in the sentence;
So after this identification, we can take different directions in our code
Checking with if/else, for example, with the return value of indexOf. Isn’t that cool?
Using the help of the indexOf method, we will receive a return of what we are looking for
If it shows -1, the word or text does not exist in the string we are checking
If another number is presented, it exists, and this number is the index of where the text we are looking for starts