How to find contains string in Javascript

If you’re looking for a way to check if a string contains a specific word or phrase, there are a few different methods you can use.

Patrick Wan
1 min readJun 2, 2022
Javascript

One option is to use the indexOf() method. This method returns the index of the first occurrence of a specified word or phrase in a string. If the word or phrase is not found, it returns -1.

For example, let’s say we have the following string:

var str = “The quick brown fox jumps over the lazy dog”;

We can use the indexOf() method to check if the string contains the word “fox”:

var index = str.indexOf(“fox”); // it will return 16, because it is was foundvar index = str.indexOf(“fax”); // it will return -1, because it is not found

If the word “fox” is found, the index variable will be set to the index of the word “fox” in the string (in this case, 16). If the word is not found, the index variable will be set to -1.

--

--

Patrick Wan
Patrick Wan

Written by Patrick Wan

My name’s Patrick. I’m a Software Developer, experience in Laravel, Vue Js, React Js, Livewire, Jquery, Codegniter, NPM, GIT. I have 5 years plus experience.