JavaScript

How to find a word in a string with JavaScript

November 2, 2021

How to find a word in a string with JavaScript

In this article, we’ll learn how to find a word in a string running the JavaScript language easily, using a native JavaScript method.

How to find a word in a string cover

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

And we can solve these two problems running JavaScript’s indexOf method.

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.

Conclusion

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

Want to take your JavaScript skills to the next level? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x