How to check whether a string contains a substring in JavaScript?

Snippets Of JavaScript
Using includes() or indexOf() to check for a string within a string in Javascript.

For all modern browsers that support ECMAScript 6 (or es6) you should use the includes() method to find a string within another string. For older browsers, like Internet explorer, that don't support Es6 you'll need to use the indexOf() method.

includes()

The includes() method performs a case-sensitive search to determine whether one string may be found within another string, returning true or false as appropriate.

const myString = "Philippines";
const mySubstring = "pine";

myString.includes(mySubstring); // true
                

If you want to do a case-insensitve search you'll need to uppercase (or lowercase) both strings before searching.

const myString = "PhiliPPines";
const mySubstring = "PINE";

myString.toUpperCase().includes(mySubstring.toUpperCase()); // true
                

indexOf()

The indexOf() method searches a string, and returns the index of the first occurrence of the specified substring or -1 if not found.

indexOf() is also case-sensitive so for case-insensitve searches you need to uppercase or lowercase both strings before testing as described above.

const myString = "Philippines";
const mySubstring = "pine";

myString.indexOf(mySubstring) !== -1; // true