Topic 39 of 87
String Search
Overview
Finding out if a string contains a specific word, finding its exact position, or replacing it with something else.
Historically, developers used indexOf() for searching. ES6 introduced modern boolean methods like includes(), startsWith(), and endsWith() which are much more readable for logic checks.
Syntax
Finding Positions (Legacy)
javascript
const str = "Please locate where 'locate' occurs!";
// Returns the index of the FIRST occurrence (or -1 if not found)
console.log(str.indexOf("locate")); // 7
// Returns the index of the LAST occurrence
console.log(str.lastIndexOf("locate")); // 21Modern ES6 Boolean Searches
javascript
const str = "Hello world, welcome to the universe.";
console.log(str.includes("world")); // true
console.log(str.startsWith("Hello")); // true
console.log(str.endsWith("universe.")); // trueReplacing Content
javascript
const text = "I love cats. Cats are great.";
// replace() only replaces the FIRST match by default!
console.log(text.replace("cats", "dogs"));
// "I love dogs. Cats are great."
// ES2021 introduced replaceAll()
console.log(text.replaceAll("cats", "dogs")); // Case sensitive!
// "I love dogs. Cats are great."Common Pitfalls
- Using
indexOfinside anifstatement incorrectly.indexOfreturns0if the match is at the very beginning of the string. Since0is falsy,if (str.indexOf('Hello'))will fail even though the string starts with 'Hello'. Always useif (str.indexOf('Hello') !== -1)or just useincludes().
Interview Questions
Q:
Why was
.includes() introduced if we already had .indexOf()?A:
.indexOf() returns a number (the index, or -1 if not found), which is clunky for simple true/false logic checks and can cause bugs with 0 being falsy. .includes() returns a clean boolean.
Real-World Example
Checking if a URL string provided by a user is secure before rendering an image.
example
javascript
if (imageUrl.startsWith("https://")) {
renderImage(imageUrl);
} else {
showSecurityWarning();
}Check Your Knowledge
Test your understanding of String Search with these quick questions.