Borislav Hadzhiev
Sun Oct 03 2021·2 min read
Photo by Jessie McCall
Use the String.includes
method to check if a substring is contained in a
javascript string, e.g. myString.includes('substring')
. The String.includes
method returns true
if the substring is contained in the string and false
otherwise.
// Not Supported in IE 6-11 const string = 'hello world'; const substring = 'hello'; console.log(string.includes(substring)); // 👉️ true if (string.includes(substring)) { // 👉️ substring is contained in string }
In the example, we've invoked the String.includes method with a substring.
If the substring is contained in the string, the String.includes
method
returns true
, otherwise it returns false
.
String.includes
method is case sensitive. To do a case insensitive check if a substring is contained in a string, convert both strings to lowercase.const string = 'HELLO world'; const substring = 'hello'; // 👇️ true console.log(string.toLowerCase().includes(substring.toLowerCase())); if (string.toLowerCase().includes(substring.toLowerCase())) { // 👉️ substring is contained in string }
To check if a substring is contained in a JavaScript string:
indexOf
method on the string, passing it the substring as a
parameter - string.indexOf(substring)
-1
-1
, the string contains the substring// Supported in IE 6-10 const string = 'hello world'; const substring = 'hello'; const index = string.indexOf(substring); console.log(index); // 👉️ 0 if (string.indexOf(substring) !== -1) { // 👉️ substring is contained in string }
String.indexOf
method returns the starting index of the substring or -1
if the substring is not contained in the stringIn the code snippet, the substring is contained in the string, starting at index
0
, therefore the
indexOf
method returns 0
.
The code block of our if
conditional check does not run if String.indexOf
returns -1
, which happens when the substring is not contained in the string.
String.indexOf
method. In any other case the String.includes
method is much more intuitive and readable.