JavaScript offers several built-in methods for locating sub-strings, validating string prefixes/suffixes, and matching patterns using regular expressions.
flowchart TD
Search["String Search Methods"] --> Predicate["Boolean Check: includes(), startsWith(), endsWith()"]
Search --> Position["Index Location: indexOf(), lastIndexOf(), search()"]
Search --> Extract["Pattern Match: match(), matchAll()"]
| Method | Return Type | Accepts RegExp? | Primary Use Case |
|---|---|---|---|
includes(substring) |
boolean |
No | Quick existence check. |
startsWith(prefix) |
boolean |
No | Validating URL schemes, prefixes, or headers. |
endsWith(suffix) |
boolean |
No | Validating file extensions (.png, .json). |
indexOf(substring) |
number (-1 if absent) |
No | Locating first occurrence index. |
search(regexp) |
number |
Yes | Locating index of first regex match. |
match(regexp) |
Array / null |
Yes | Extracting matched strings or groups. |
// Demonstrating JavaScript string searching techniques
const logEntry = "2026-08-13 [ERROR] Database connection failed to host 192.168.1.50";
// 1. Boolean Predicate Checks
console.log(`Contains 'ERROR': ${logEntry.includes("[ERROR]")}`); // true
console.log(`Starts with timestamp: ${logEntry.startsWith("2026")}`); // true
console.log(`Ends with IP: ${logEntry.endsWith("192.168.1.50")}`); // true
// 2. Index Finding
const errorIndex = logEntry.indexOf("[ERROR]");
console.log(`Index of '[ERROR]': ${errorIndex}`); // 11
const missingIndex = logEntry.indexOf("[WARN]");
console.log(`Index of missing substring: ${missingIndex}`); // -1
// 3. Regular Expression Search and Match
const ipPattern = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/;
const matchedIp = logEntry.match(ipPattern);
if (matchedIp) {
console.log(`Extracted IP Address: ${matchedIp[0]}`);
}
// 4. Case-Insensitive Search
const lowerMsg = "JavaScript Tutorial";
console.log(`Search 'javascript' (case-insensitive): ${/javascript/i.test(lowerMsg)}`);
includes() Over indexOf() !== -1: includes() is more readable and explicitly returns a boolean.indexOf() Returns -1 When Not Found: Always check if index !== -1 before using index values for slicing.Write a function isImageFile(filename) that returns true if filename ends with .jpg, .jpeg, .png, or .webp (case-insensitive).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.