indexOf() JavaScript String Method – How to Get Text Index
Whenever you use indexOf() on a string, the method does the following:
- It searches its calling string for the method's first argument.
- It returns the index of the first match, or
-1
if the method found no match.
note
- A calling string is a string on which you used
indexOf()
. So, in"Hello, world!".indexOf("world")
,"Hello, world!"
is the calling string. indexOf()
is sometimes written asString.prototype.indexOf()
because it is a method of theString
object'sprototype
property.
Syntax of the indexOf()
Method
indexOf()
accepts two arguments. Here is the syntax:
callingString.indexOf(valueToFind, startIndex);
Argument 1: valueToFind
A valueToFind
is the first argument accepted by the indexOf()
method. It defines the value you wish to find in the calling string.
Example 1: Find the index of day
"SunDay, Tuesday, and Friday are good Days".indexOf("day");
// The invocation above will return: 12
Example 2: Find the index of Day
"SunDay, Tuesday, and Friday are good Days".indexOf("Day");
// The invocation above will return: 3
Example 3: Find the index of 3
"Day1, day-3, and day 6 are good Days".indexOf(3);
// The invocation above will return: 10
Argument 2: startIndex
The startIndex
argument is optional. It specifies the index where you want the computer to start searching for the valueToFind
argument.
Example 1: Find the index of day
from the 13th index
"SunDay, Tuesday, and Friday are good Days".indexOf("day", 13);
// The invocation above will return: 24
The startIndex
argument's default value is 0
. Therefore, if omitted or negative, the search will begin at index 0
.
Here's an example:
"SunDay, Tuesday, and Friday are good Days".indexOf("day", -13);
// The invocation above will return: 12
Example 2: Find the index of Day
from the 4th index
"SunDay, Tuesday, and Friday are good Days".indexOf("Day", 4);
// The invocation above will return: 37
Suppose startIndex
is greater than the calling string's length. In such a case, the computer will ignore the search.
Here's an example:
"SunDay, Tuesday, and Friday are good Days".indexOf("Day", 75);
// The invocation above will return: -1
tip
- To find the last occurrence of a substring within a string, use
lastIndexOf()
. - Suppose you need to use regular expression as the
valueToFind
argument. In that case, usesearch()
. - To do a global search for all matches, use
match()
. - You can also use
indexOf()
on an array.
Overview
indexOf()
searches its calling string for the first occurrence of the method's string argument.