The includes() method is useful for determining if a string contains a predetermined value.
boolValue = MyString.includes("A String");
Note: This method will return a boolean value.
The example below demonstrates a typical use case for the includes() method.
var MyString = "Hello World!";
var TestString = "llo W";
var TestResult = MyString.includes(TestString);
if (TestResult){
console.log("The String: \'" + MyString + "\' contains:\'" + TestString + "\'");
}else{
console.log("The String: \'" + MyString + "\' does not contain:\'" + TestString + "\'");
}
The following is printed to the console:
The String: 'Hello World!' contains:'llo W'
Using the Optional Start Position Value
boolValue = MyString.includes("A String", 10);
You can optionally include a start position value with the includes() method.
It is important to know that the start position is an index value that starts at zero.
This can be confusing, as demonstrated below:
var MyString = "ABCD";
var TestString = "B";
var StartPosition = 2;
var TestResult = MyString.includes(TestString,StartPosition);
//TestResult will be false because MyString[2] == "C"
if (TestResult){
console.log("The String: \'" + MyString + "\' contains:\'" + TestString + "\' at the start position of : " + StartPosition);
}else{
console.log("The String: \'" + MyString + "\' does not contain:\'" + TestString + "\' at the start position of : " + StartPosition);
}
The following is printed to the console:
The String: 'ABCD' does not contain:'B' at the start position of : 2
Tip: Using a value for the start position that is larger than the length of the string does not generate a warning or an error, but the method will always return false.
Passing a Null Value As a Parameter to the includes() Method
One quirky thing to note about this method is that if you attempt to evaluate the following code:
x = MyString.includes("");
Then the value of the variable x will always be true no matter what the contents of MyString is.
Even a string that is empty will contain “” according to the includes() method.