How to search for word in strings with JavaScript

November 23, 2021

How to search for word in strings with JavaScript

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.

how to search for word in strings cover

Hey you programmer, okay? Let’s learn something new!

Searching for words in a string is very easy in JavaScript

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?


We learned in this article that it is possible to search for words in strings with the JavaScript language

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

Want to learn more about JavaScript? Click here!

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x