How to Find Substring in JavaScript: Simple Methods Explained
In JavaScript, you can find a substring using the
includes() method to check if it exists, or indexOf() to get its position. Both methods work on strings and help you locate parts of text easily.Syntax
The two main methods to find a substring in JavaScript are includes() and indexOf().
string.includes(substring): Returnstrueifsubstringis found, otherwisefalse.string.indexOf(substring): Returns the starting index ofsubstringif found, otherwise-1.
javascript
let text = "Hello, world!"; // Check if 'world' is in text let hasWorld = text.includes("world"); // Find position of 'world' let position = text.indexOf("world");
Example
This example shows how to check if a substring exists and find its position in a string.
javascript
const sentence = "I love learning JavaScript!"; // Check if 'JavaScript' is in the sentence const containsJS = sentence.includes("JavaScript"); console.log(containsJS); // true // Find the starting index of 'learning' const indexLearning = sentence.indexOf("learning"); console.log(indexLearning); // 7 // Try to find a substring that does not exist const indexPython = sentence.indexOf("Python"); console.log(indexPython); // -1
Output
true
7
-1
Common Pitfalls
One common mistake is expecting indexOf() to return true or false instead of a number. Remember, it returns -1 if the substring is not found.
Also, includes() is case-sensitive, so "Hello" and "hello" are different.
javascript
const text = "Hello World"; // Wrong: expecting boolean from indexOf if (text.indexOf("world") !== -1) { console.log("Found it!"); } else { console.log("Not found."); } // Right way if (text.indexOf("world") !== -1) { console.log("Found it!"); } else { console.log("Not found."); } // Case sensitivity example console.log(text.includes("world")); // false console.log(text.includes("World")); // true
Output
Found it!
Not found.
false
true
Quick Reference
| Method | Description | Return Value | Case Sensitive |
|---|---|---|---|
| includes(substring) | Checks if substring exists | true or false | Yes |
| indexOf(substring) | Finds starting index of substring | Index number or -1 | Yes |
Key Takeaways
Use
includes() to check if a substring exists, returning true or false.Use
indexOf() to find the position of a substring; it returns -1 if not found.Both methods are case-sensitive, so watch your letter cases.
Remember
indexOf() returns a number, not a boolean.For simple substring checks,
includes() is more readable and direct.