JAVASCRIPT

JavaScript String indexOf method: Syntax, Usage, and Examples

The indexOf() method in JavaScript allows you to find the position of a substring within a string. It returns the index of the first occurrence or -1 if the substring doesn’t exist. The JavaScript string indexOf method is a powerful and efficient way to search inside strings and is commonly used in text processing, filtering, and validation.

How to Use JavaScript String indexOf

Here’s the basic syntax:

string.indexOf(searchValue, startIndex)
  • searchValue: The substring you’re looking for.
  • startIndex: Optional. The position to start the search from. Defaults to 0.

The method returns the index of the first match or -1 if no match is found.

Basic Example

const message = "Hello, world!";
console.log(message.indexOf("world")); // Output: 7

The word "world" starts at index 7 in the string.

When to Use string indexOf JavaScript

This method works best when:

You Need to Check If a Substring Exists

const email = "example@gmail.com";

if (email.indexOf("@") !== -1) {
  console.log("Valid email format.");
}

This helps in validating inputs like emails, URLs, or tags.

You Want to Extract Data Based on Location

const sentence = "The price is $29.99";
const dollarSign = sentence.indexOf("$");

if (dollarSign !== -1) {
  const price = sentence.slice(dollarSign);
  console.log(price); // "$29.99"
}

Knowing the index lets you slice or replace parts of the string accurately.

You Need to Count or Remove Substrings

Find out how many times a word appears, or where it appears, by using this method in a loop.

Examples of JavaScript string indexOf in Practice

Finding a Word in a Sentence

const quote = "To be or not to be";
console.log(quote.indexOf("be")); // 3

The first instance of "be" is at index 3.

Start Search from a Specific Index

const text = "one fish two fish red fish blue fish";
console.log(text.indexOf("fish"));      // 4
console.log(text.indexOf("fish", 10));  // 13

This lets you skip earlier results and find the next occurrence.

Case Sensitivity

const greeting = "Hello World";
console.log(greeting.indexOf("world")); // -1

The method is case-sensitive. Convert both strings to lowercase if needed:

greeting.toLowerCase().indexOf("world"); // 6

Learn More About indexOf in JavaScript String

Using indexOf with Conditional Logic

const username = "john_doe";

if (username.indexOf("admin") === -1) {
  console.log("Standard user.");
} else {
  console.log("Admin user detected.");
}

Quickly route logic based on substring presence.

Replace or Modify Based on indexOf

const path = "/user/settings";
const settingsIndex = path.indexOf("settings");

if (settingsIndex !== -1) {
  const basePath = path.slice(0, settingsIndex);
  console.log(basePath); // "/user/"
}

Great for URL manipulation and route detection.

Use in Loops to Count All Occurrences

const data = "banana";
let pos = data.indexOf("a");
let count = 0;

while (pos !== -1) {
  count++;
  pos = data.indexOf("a", pos + 1);
}

console.log(count); // 3

Loop through multiple matches with startIndex.

Combine with substr, slice, or substring

const fullName = "Jane Smith";
const spaceIndex = fullName.indexOf(" ");

const firstName = fullName.slice(0, spaceIndex);
const lastName = fullName.slice(spaceIndex + 1);

console.log(firstName); // "Jane"
console.log(lastName);  // "Smith"

By locating the space, you can split names easily.

Comparing indexOf and includes()

While includes() checks for presence and returns a boolean, indexOf() tells you exactly where the match is:

const message = "Welcome back!";

message.includes("back");       // true
message.indexOf("back");        // 8

Use includes() for readability, but stick with indexOf() when you need the index.

Nested Searches and Edge Cases

If the target substring appears at index 0, a truthy check like if (str.indexOf("x")) will fail because 0 is falsy. Use explicit comparisons:

if (str.indexOf("x") !== -1) {
  // correct
}

Avoid mistakes by checking directly against -1.

JavaScript string indexOf with Dynamic Search Values

const keyword = "book";
const phrase = "She read a book by the river";

if (phrase.indexOf(keyword) !== -1) {
  console.log("Keyword found");
}

Whether hardcoded or dynamic, this method adapts easily to user-driven content.

Searching for Characters

Not just for words—you can search for characters too:

const phone = "(555) 123-4567";
const dashIndex = phone.indexOf("-");

console.log(dashIndex); // 9

Use it to clean data, extract phone numbers, or parse symbols.

Pairing indexOf with Regular Expressions

While indexOf() doesn’t accept regex, it’s often used together with .match() or .replace() for custom patterns. Use indexOf() when searching for exact substrings; use regex when you need patterns.

The JavaScript string indexOf method provides a fast, flexible way to find characters or words within strings. From email validation to string slicing, it's a dependable tool in your everyday coding toolkit. Developers frequently rely on it to build search features, clean up data, and trigger dynamic behaviors based on content. With proper use, it keeps your string manipulation logic both simple and precise.

Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH