The indexOf() method is useful for determining the index at which a string starts at, if that string is contained inside another string.
MyIndex = MyString.indexOf("Test");
If the string that is passed as a parameter to the indexOf() method does not exist in the string, then the method will return negative one.
The example below demonstrates a typical use case for the indexOf() method.
var MyString = "Hello World!";
var TestString = "llo W";
var TestResult = MyString.indexOf(TestString);
if (TestResult >= 0){
console.log("The String: \'" + MyString + "\' contains:\'" + TestString + "\' at position: " + TestResult);
}else{
console.log("The String: \'" + MyString + "\' does not contain:\'" + TestString + "\'");
}
The following is printed to the console:
The String: 'Hello World!' contains:'llo W' at position: 2
Using the Optional Start Position Value Parameter
You can optionally include a start position value with the indexOf() 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 = "C";
var StartPosition = 2;
//TestString[2] == C;
var TestResult = MyString.indexOf(TestString,StartPosition);
if (TestResult >= 0){
console.log("The String: \'" + MyString + "\' contains:\'" + TestString + "\' at the position of : " + TestResult);
}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' contains:'C' at the 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 negative one.
Passing a Null Value As a Parameter to the includes() Method
This method will behave in a way that is quirky and undesirable if you accidentally pass an empty string as a parameter.
In the line of code below, the value of x will always be equal to 0, no matter what the value of MyString is.
x = MyString.indexOf("");
includes() Method Vs indexOf() Method
These two methods are similar and both can be used to determine if a specific string contains another string, but there are some differences.
The includes() method returns a boolean value compared to the indexOf() method, which returns a number.
The following code below is identical in functionality, although using indexOf() is less efficient as the index value is not used in the example.
MyString = "The Sky is Blue.";
TestString = "Sky";
//two different ways to do the same test
if (MyString.includes(TestString)) {
//do something
}
//the code below is functionally indentical to the code above
if (MyString.indexOf(TestString) >= 0) {
//do something
}