The includes() Method
includes() method. To use this method, pass it after the string in question using a
. (dot) and inside the parenthesis of
includes() pass the substring you want to look for.
var string = 'this is some text'; var result = string.includes('text'); console.log(result);
includes() provides a boolean
false response if the presence of a substring is found.
Case insensitive Substring Search
includes() method is case sensitive. If you would like to perform a case insensitive check, convert both the string to search and value to check into lowercase using the
var string = 'this is some text'; value = 'TeXt'.toLowerCase(); var result = string.toLowerCase().includes(value); console.log(result);
Set a Starting Position to Check from
includes() method accepts a second optional argument that specifies where to begin looking for a substring in the string. This numerical value represents the character position to check after.
var string = 'this is some text'; var result = string.includes('his', 1); var result_2 = string.includes('his', 2); console.log(result); console.log(result_2);
includes() is supported by all modern browsers, however, if you need to be absolutely sure that checking for substrings works for users with outdated browsers use the
indexOf() method. Here is are a couple of examples of
indexOf() in action:
var string = 'this is some text'; var result = string.indexOf('his') !== -1; var result_2 = string.indexOf('his', 2) !== -1; console.log(result); console.log(result_2);