Mohan pd.
Mohan pd. Author of The Coders Blog. Also a professional fullstack javascript developer working with various tech company and client around world.

Best way to check if a string contains a specific word or substring in JavaScript

Feb 20, 2019 · 1 min
Best way to check if a string contains a specific word or substring in JavaScript

Here are the methods available in js to find substring and word.

You can save a picture for quick reference

1 You can use four different methods to check it a string contains another word or sub-string These methods are: indexOf(), includes(), </code>search()</code> and match().

2 The indexOf() method win return the index or the matched string while includes() just returns a Boolean True or False: You can use them both without worrying too much about performance. Both these methods are case-sensitive.

3 If you me planning lo perform case insensitive searches, using search() with the case-insensitive flag it might be a better Idea. However, you will have to escape some special characters for the search to be successful. Using the search() method also gives you more flexibility over simple stung matching methods indexOf() and includes().

4. You can also use match() to see If a string has another word or sub string However. it you Just want to know it a match exists, using it might be an overkill.