JavaScript String indexOf() and lastIndexOf()

indexOf() returns the zero-based position of the first occurrence of text inside a string. If the text is not found, it returns -1.

const text = "www.plus2net.com";
console.log(text.indexOf("plus")); // 4

indexOf() Syntax and Return Value Top ↑

string.indexOf(searchString)
string.indexOf(searchString, position)

The optional position controls where the forward search begins.

When indexOf() Does Not Find the Text Top ↑

const text = "www.plus2net.com";
console.log(text.indexOf("python")); // -1

Start Searching from a Specific Position Top ↑

const text = "one two one";
console.log(text.indexOf("one"));    // 0
console.log(text.indexOf("one", 1)); // 8

Find the Last Occurrence with lastIndexOf() Top ↑

The original page also teaches lastIndexOf(), which returns the last matching position.

const text = "Welcome to www.plus2net.com";
console.log(text.lastIndexOf("l")); // last l position

indexOf() vs includes() Top ↑

Use indexOf() when you need the numeric position. Use includes() when you only need a Boolean answer.

const text = "JavaScript tutorial";
console.log(text.indexOf("Script")); // 4
console.log(text.includes("Script")); // true

String Searches Are Case-Sensitive Top ↑

const text = "JavaScript";
console.log(text.indexOf("java")); // -1
console.log(text.toLowerCase().indexOf("java")); // 0

Searching for an Empty String Top ↑

An empty search string is considered to occur at a valid position within the string, so it does not behave like “not found.”

const text = "abc";
console.log(text.indexOf("")); // 0

Practical Example: Find the @ in an Email-Like Value Top ↑

const email = "userid@example.com";
const at = email.indexOf("@");
console.log(at);

See the email user/domain string example for combining index lookup with extraction.

Common indexOf() Mistakes Top ↑

  • Using if (text.indexOf(value)); index 0 is falsy and -1 is truthy.
  • Forgetting that matching is case-sensitive.
  • Expecting a Boolean instead of a numeric index.
  • Using indexOf() when a regular-expression search is required; see search().

String Reference Email String Example




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer