JavaScript Notes
Master JavaScript string searching: includes(), indexOf(), lastIndexOf(), startsWith(), endsWith(), search(), match() with visual comparisons and real-world examples.
Why String Searching?
Searching inside strings is one of the most common tasks in web development: validating emails, checking if a URL contains a path, finding keywords in text, autocomplete features, filtering lists — all rely on string searching methods.
Think of string searching like a Ctrl+F on text: you tell JavaScript what to look for and it tells you whether it found it, and if so, where.
includes() — Does it Contain?
Returns true or false. The simplest and most readable way to check if a string is present.
const title = "JavaScript Master Course";
console.log(title.includes("Master")); // found
console.log(title.includes("Python")); // not found
console.log(title.includes("javascript")); // case-sensitive!
console.log(title.includes("Java", 5)); // search from index 5true false false false
⚠️ includes() is case-sensitive. "java" ≠ "Java".Case-insensitive check
const bio = "I love JavaScript and TypeScript";
const keyword = "typescript";
const found = bio.toLowerCase().includes(keyword.toLowerCase());
console.log(found);true
indexOf() — Where is it?
Returns the starting index of the first match, or -1 if not found.
const str = "Hello JavaScript, Hello World";
// 0 6 1 1
// 0 6 7 8
console.log(str.indexOf("Hello")); // first occurrence
console.log(str.indexOf("Hello", 5)); // search from index 5
console.log(str.indexOf("Python")); // not found
console.log(str.indexOf("JavaScript")); // starting position0 18 -1 6
Using indexOf() to check existence
const fruits = "apple,mango,banana,grapes";
// Old way (before includes was added in ES6)
if (fruits.indexOf("mango") !== -1) {
console.log("Mango found!");
}
// Modern way
if (fruits.includes("mango")) {
console.log("Mango found (modern)!");
}Mango found! Mango found (modern)!
lastIndexOf() — Where is the Last One?
Returns the index of the last occurrence, or -1 if not found.
const email = "user.name@company.com";
const lastDot = email.lastIndexOf(".");
console.log(lastDot);
// Get the file extension
const filename = "report.final.v2.pdf";
const ext = filename.slice(filename.lastIndexOf(".") + 1);
console.log(ext);17 pdf
startsWith() — Does it Begin With?
const url = "https://www.wohotech.in/javascript";
console.log(url.startsWith("https")); // secure protocol?
console.log(url.startsWith("http://")); // not https
console.log(url.startsWith("www", 8)); // start checking from index 8true false true
Practical: Validate URL protocol
function isSecure(url) {
return url.startsWith("https://");
}
console.log(isSecure("https://example.com")); // true
console.log(isSecure("http://example.com")); // falsetrue false
endsWith() — Does it End With?
const fileName = "project-report.pdf";
console.log(fileName.endsWith(".pdf")); // is it a PDF?
console.log(fileName.endsWith(".docx")); // is it Word?
console.log(fileName.endsWith("report", 14)); // check up to index 14true false true
Practical: File type validation
true false true
search() — indexOf with Regex Power
Like indexOf() but accepts regular expressions. Returns the index or -1.
const text = "Contact us at: support@example.com or sales@example.com";
// Search for first email pattern
const emailPos = text.search(/@\w+\.\w+/);
console.log(emailPos);
// Simple string also works (but use indexOf for strings)
console.log(text.search("support"));24 15
match() — Find All Matches
Returns an array of matches (null if no match). Supports regex for powerful pattern matching.
[ '100', '250', '75', '1000' ] 100 9
Find all emails in text
[ 'info@example.com', 'support@wohotech.com' ]
Comparison Table — All Searching Methods
| Method | What it returns | Use when |
|---|---|---|
includes(str) | true / false | You just need yes/no |
indexOf(str) | Index or -1 | You need the position too |
lastIndexOf(str) | Index or -1 | You need the LAST position |
startsWith(str) | true / false | Checking the beginning |
endsWith(str) | true / false | Checking the end (file ext, etc.) |
search(regex) | Index or -1 | Pattern-based position search |
match(regex) | Array or null | Collecting all matches |
Real World Use Cases 🌍
1. Search filter (autocomplete)
[ 'JavaScript Basics', 'JavaScript Advanced' ] [ 'Node.js Masterclass' ]
2. URL analysis
const url = "https://api.example.com/users?page=2&limit=10";
console.log(url.startsWith("https")); // secure?
console.log(url.includes("/users")); // is it the users endpoint?
console.log(url.indexOf("?")); // where do query params start?
const queryString = url.slice(url.indexOf("?") + 1);
console.log(queryString);true true 38 page=2&limit=10
3. Validate email format
function isValidEmail(email) {
return email.includes("@") && email.includes(".") &&
email.indexOf("@") > 0 &&
email.lastIndexOf(".") > email.indexOf("@");
}
console.log(isValidEmail("user@example.com")); // true
console.log(isValidEmail("userexample.com")); // false — no @
console.log(isValidEmail("@example.com")); // false — no local parttrue false false
Common Mistakes ❌
1. Case sensitivity trap
// ❌ Wrong — not accounting for case
const msg = "Welcome to WoHoTech";
console.log(msg.includes("wohotech")); // false!
// ✅ Correct — normalize case first
console.log(msg.toLowerCase().includes("wohotech")); // true2. Confusing indexOf result for boolean
// ❌ Wrong — 0 is falsy!
const str = "JavaScript";
if (str.indexOf("Java")) {
console.log("Found!"); // WRONG: index 0 is falsy, won't run
}
// ✅ Correct — check for -1
if (str.indexOf("Java") !== -1) {
console.log("Found!"); // Correct
}
// ✅ Best — use includes()
if (str.includes("Java")) {
console.log("Found!"); // Cleanest
}3. Using search() for plain strings
// ❌ Overkill for plain strings
const pos = text.search("hello");
// ✅ Better — use indexOf for plain strings
const pos2 = text.indexOf("hello");
// Use search() only when you need regexInterview Questions 🎯
Q1. What is the difference between includes() and indexOf()? > includes() returns a boolean (true/false). indexOf() returns the index of the first match or -1. Use includes() when you only need to know if something exists; use indexOf() when you need the position.
Q2. Why can if (str.indexOf("x")) fail? > Because indexOf returns 0 when the match is at the start of the string, and 0 is falsy in JavaScript. Always compare with !== -1.
Q3. Are string searching methods case-sensitive? > Yes — all of them. Convert both strings to the same case (.toLowerCase()) before searching for case-insensitive comparisons.
Q4. What does match() return when there is no match? > null. Always check for null before accessing results: const m = str.match(regex); if (m) { ... }.
Q5. What is the difference between search() and indexOf()? > Both return the index of the first match or -1. indexOf() works with strings only. search() works with regular expressions and is the regex-aware version.
Q6. How do you find the file extension from a filename string? > filename.slice(filename.lastIndexOf(".") + 1) — find the last dot, then slice everything after it.
Q7. What does startsWith(str, position) do with the second argument? > It starts the search from the given position index, treating that position as the start of the string for the check.
Key Takeaways 🏁
includes()= simplest, returns boolean — use this most oftenindexOf()= returns position or -1 — check!== -1, not just truthystartsWith/endsWith()= perfect for protocol checks, file extensionslastIndexOf()= great for getting file extensions or last occurrence- All are case-sensitive — lowercase both sides for case-insensitive search
match(regex)= most powerful — returns array of matches withgflagsearch(regex)= use when you need regex AND a position
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript String Searching Methods - includes, indexOf, startsWith, match Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, strings, string, searching
Related JavaScript Master Course Topics