String .indexOf() / lastIndexOf() / includes()
Searches for a specified string within a string and returns its position. If you only need to check whether a string exists, string.includes() is more convenient.
Syntax
// Searches from the beginning and returns the position of the first match.
string.indexOf("searchString")
string.indexOf("searchString", startPosition)
// Searches from the end and returns the position of the last match.
string.lastIndexOf("searchString")
string.lastIndexOf("searchString", startPosition)
// Returns true or false depending on whether the string is found.
string.includes("searchString")
string.includes("searchString", startPosition)
Method List
| Method | Description |
|---|---|
| indexOf("searchString") | Searches from the beginning and returns the index of the first match. Returns -1 if not found. |
| indexOf("searchString", startPosition) | Starts the search from the specified position. |
| lastIndexOf("searchString") | Searches from the end and returns the index of the last match. Returns -1 if not found. |
| includes("searchString") | Returns true if the string is found, or false if it is not. |
| includes("searchString", startPosition) | Starts the search from the specified position. |
Sample Code
var str = "JavaScript is great. JavaScript is fun.";
// Use indexOf to get the position of the first match.
console.log(str.indexOf("JavaScript")); // Outputs 0.
console.log(str.indexOf("is")); // Outputs 11.
console.log(str.indexOf("Python")); // Not found, so outputs -1.
// The second argument specifies the starting position for the search.
console.log(str.indexOf("JavaScript", 1)); // Outputs 21.
// Use lastIndexOf to get the position of the last match.
console.log(str.lastIndexOf("JavaScript")); // Outputs 21.
// Use includes to check whether a string exists.
console.log(str.includes("great")); // Outputs true.
console.log(str.includes("Python")); // Outputs false.
Overview
string.indexOf() and string.lastIndexOf() are methods that search for a specified string within a string and return its position (index) as a number. string.indexOf() searches from the beginning, while string.lastIndexOf() searches from the end. Both return -1 if the string is not found.
When you only need to check whether a string is present, string.includes() returns a simple true or false, which makes your code easier to read. With string.indexOf(), you need to compare against -1, as in str.indexOf("abc") !== -1, whereas string.includes() lets you write the same check as simply str.includes("abc").
All of these methods are case-sensitive. If you need a case-insensitive search, convert the string to lowercase first using string.toLowerCase() before searching.
Browser Compatibility
2 or earlier ×
2 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.