JavaScript provides several methods that allow you to search for a specific substring (text) within a larger string. Some methods return the position (index) of the text, while others return a boolean (true/false).
These methods return the index where the search text starts. Remember that JavaScript strings use zero-based indexing (the first character is 0).
Returns the index of the first occurrence of a specified text in a
string. Returns -1 if the text is not found.
let str = "Please locate where 'locate' occurs!";
let index = str.indexOf("locate");
console.log(index); // 7
Returns the index of the last occurrence of a specified text.
let str = "Please locate where 'locate' occurs!";
let index = str.lastIndexOf("locate");
console.log(index); // 21
Searches a string for a string (or a regular expression) and returns the position of the match.
let text = "Mr. RedoHub is a developer";
console.log(text.search("RedoHub")); // 4
These modern methods are often preferred when you just need to know if a string exists, without needing its exact position.
Returns true if a string contains a specified value.
let text = "Hello world, welcome to the universe.";
console.log(text.includes("world")); // true
Returns true if a string begins with a specified value.
let text = "Hello world";
console.log(text.startsWith("Hello")); // true
Returns true if a string ends with a specified value.
let text = "Mim Akter";
console.log(text.endsWith("Akter")); // true
indexOf() and lastIndexOf() return positions (or -1)includes(), startsWith(), and endsWith() return true or falseincludes) make code much more readable than indexOf(...) !== -1