Course contentsShow
← JavaScript
Lesson 158 of 2,7235. StringsFree lesson

indexOf(): Finding the First Occurrence

Locate the position of the first occurrence of a substring, or -1 if not found.

indexOf(): Finding the First Occurrence

You'll learn how to find the exact position of the first occurrence of a substring within a string.

What indexOf() Does

The indexOf() method searches a string and returns the position (index) where a substring first appears. If the substring isn't found, it returns -1.

Think of it like searching for a word in a book: indexOf() tells you which page number the word first appears on, or signals that the word doesn't exist in the book at all.

Basic Syntax

let message = "Hello, world!";
let position = message.indexOf("world");
console.log(position); // 7

The substring "world" starts at index 7 (remember, JavaScript counts from 0).

When Substring Not Found

let text = "JavaScript is fun";
let result = text.indexOf("Python");
console.log(result); // -1

Since "Python" doesn't exist in the string, indexOf() returns -1.

Finding Single Characters

let greeting = "Hello";
console.log(greeting.indexOf("e")); // 1
console.log(greeting.indexOf("o")); // 4
console.log(greeting.indexOf("z")); // -1

Case Sensitivity Matters

let phrase = "Hello World";
console.log(phrase.indexOf("world")); // -1 (lowercase doesn't match)
console.log(phrase.indexOf("World")); // 6 (exact match)

indexOf() is case-sensitive, so capitalization must match exactly.

Optional Starting Position

You can tell indexOf() where to begin searching:

let sentence = "I love coding, I really love it";
console.log(sentence.indexOf("love"));     // 2 (first occurrence)
console.log(sentence.indexOf("love", 10)); // 22 (starts searching from index 10)

Key Takeaway: indexOf() returns the index of the first occurrence of a substring, or -1 if not found—perfect for locating specific text within strings.