Syntax
str.indexOf(substring)
str.includes(substring)
str.startsWith(substring)
str.endsWith(substring)Examples
indexOf() and includes()
Finding whether and where a substring appears.
const text = "The quick brown fox";
console.log(text.indexOf("quick")); // 4
console.log(text.indexOf("lazy")); // -1 - not found
console.log(text.includes("brown")); // true
console.log(text.includes("Brown")); // false - case-sensitivestartsWith() and endsWith()
Checking the beginning or end of a string specifically.
const filename = "report.pdf";
console.log(filename.endsWith(".pdf")); // true
console.log(filename.endsWith(".docx")); // false
console.log(filename.startsWith("report")); // true
// Common use: validating file extensions or URL prefixes
const url = "https://example.com";
console.log(url.startsWith("https://")); // trueBest practices
- Use includes() for a simple presence check instead of indexOf() !== -1 - it is more readable
- Use startsWith()/endsWith() instead of manually slicing strings to check prefixes or suffixes
- Convert both sides with toLowerCase() first if you need a case-insensitive search
- Remember all these methods are case-sensitive by default - "Hello".includes("hello") is false
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification