In JavaScript, how can I check if the string str1 contains another substring str2?

4 Answers

In JavaScript ES6, use



"hello".includes("el");      //returns true.

To make it work on older browsers, you may need to load es6-shim


I prefer using the third party-libraries like Lodash and Underscore.


_.includes('hello', 'el');


_.str.include('hello', 'el');

To do a case-insensitive search, use search() with a regular expression

var str = "Hello World";
var index =;        //returns 6

Use the str.indexOf(searchStr) method where searchStr is a string representing the value to search for in the string str.

The return value is the index of the first occurrence of the specified value. It returns -1 if the string is not found.

'Hello World'.indexOf('ello');     //returns 1
'Hello World'.indexOf('Helo');      //returns -1

You can pass an optional second parameter which is the index at which to start the searching forwards in the string.

'Hello World'.indexOf('World', 5);  //returns 6