How to Use indexOf for Search in JavaScript
Use the
indexOf method on a string to find the position of a substring. It returns the index of the first match or -1 if not found.Syntax
The indexOf method is called on a string and takes the substring you want to find as the first argument. Optionally, you can provide a second argument to specify the starting position for the search.
string.indexOf(searchValue)- searches from the start.string.indexOf(searchValue, fromIndex)- starts searching fromfromIndex.
javascript
string.indexOf(searchValue, fromIndex)
Example
This example shows how to find the position of a word inside a sentence. It also shows what happens if the word is not found.
javascript
const sentence = "Hello, welcome to JavaScript programming."; const position1 = sentence.indexOf("welcome"); console.log(position1); // 7 const position2 = sentence.indexOf("Python"); console.log(position2); // -1
Output
7
-1
Common Pitfalls
One common mistake is to check if indexOf returns true or false. Since it returns a number, you must check if the result is -1 to know if the substring was not found.
Also, remember that indexOf is case-sensitive, so searching for "Welcome" will not find "welcome".
javascript
const text = "JavaScript is fun."; // Wrong way: if (text.indexOf("script")) { console.log("Found it!"); } else { console.log("Not found."); } // Right way: if (text.indexOf("script") !== -1) { console.log("Found it!"); } else { console.log("Not found."); }
Output
Not found.
Found it!
Quick Reference
| Usage | Description |
|---|---|
| string.indexOf(substring) | Returns index of first occurrence or -1 if not found |
| string.indexOf(substring, startIndex) | Starts search at given index |
| Check result !== -1 | To confirm substring exists |
| Case-sensitive | Search matches exact letter case |
Key Takeaways
Use indexOf to find the position of a substring in a string.
indexOf returns -1 if the substring is not found.
Always check if the result is not -1 to confirm a match.
indexOf is case-sensitive; letter case must match exactly.
You can specify a starting index to begin the search.