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
string.indexOf(searchString)
string.indexOf(searchString, position)
The optional position controls where the forward search begins.
const text = "www.plus2net.com";
console.log(text.indexOf("python")); // -1
const text = "one two one";
console.log(text.indexOf("one")); // 0
console.log(text.indexOf("one", 1)); // 8
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
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
const text = "JavaScript";
console.log(text.indexOf("java")); // -1
console.log(text.toLowerCase().indexOf("java")); // 0
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
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.
if (text.indexOf(value)); index 0 is falsy and -1 is truthy.indexOf() when a regular-expression search is required; see search().String Reference Email String Example
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.