Codectionary / Developer documentation / JavaScript

indexOf(), includes(), startsWith(), endsWith()

These methods search within a string for a substring. indexOf() returns the position of the first match (or -1). includes() returns a simple true/false. startsWith() and endsWith() check specifically whether the string begins or ends with a given substring. All are case-sensitive.

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-sensitive

startsWith() 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://")); // true

Best 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

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation