JavaScript String Search
8 April 2025 | Category: JavaScript
In JavaScript, you often need to search for a specific word or pattern inside a string. JavaScript provides several methods to help you find, locate, or match parts of a string easily.
✅ Why Use String Search Methods?
Whether you’re checking if a word exists in a sentence, finding the position of a character, or matching a pattern using regular expressions, JavaScript’s string search tools have you covered.
🔹 1. indexOf()
– Finds the first occurrence
let text = "I love JavaScript!";
console.log(text.indexOf("JavaScript")); // Output: 7
- Returns the index of the first match.
- Returns
-1
if the text is not found.
🔹 2. lastIndexOf()
– Finds the last occurrence
let text = "I love JavaScript. JavaScript is fun!";
console.log(text.lastIndexOf("JavaScript")); // Output: 18
- Useful when a word appears multiple times.
🔹 3. search()
– Searches using a regular expression
let text = "I love JavaScript!";
console.log(text.search(/script/i)); // Output: 10
i
makes the search case-insensitive.- Similar to
indexOf
, but more powerful with regex.
🔹 4. includes()
– Checks if a string contains a value
let text = "Hello world!";
console.log(text.includes("world")); // Output: true
- Returns a boolean (
true
orfalse
). - Case-sensitive.
🔹 5. startsWith()
– Checks if string starts with given value
let text = "JavaScript is awesome!";
console.log(text.startsWith("Java")); // Output: true
- You can also pass a start position as the second argument.
🔹 6. endsWith()
– Checks if string ends with given value
let text = "Learn JavaScript";
console.log(text.endsWith("Script")); // Output: true
- Can also be used with a length argument to test within a portion of the string.
✨ Bonus: Using Regular Expressions with match()
let text = "The rain in Spain";
let result = text.match(/ain/g);
console.log(result); // Output: ["ain", "ain"]
match()
finds all matches of a pattern.g
is the global flag (find all, not just the first).
🧠 Summary Table
Method | Description | Returns |
---|---|---|
indexOf() | First position of a match | Number (-1 if not found) |
lastIndexOf() | Last position of a match | Number |
search() | Search using regex | Number |
includes() | Checks if string contains value | Boolean |
startsWith() | Checks beginning of string | Boolean |
endsWith() | Checks end of string | Boolean |
match() | Finds matches using regex | Array or null |