HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript String Search

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).


Finding the Position (Index)

These methods return the index where the search text starts. Remember that JavaScript strings use zero-based indexing (the first character is 0).

1. indexOf()

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

2. lastIndexOf()

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

3. search()

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

Boolean Results (ES6+)

These modern methods are often preferred when you just need to know if a string exists, without needing its exact position.

1. includes()

Returns true if a string contains a specified value.

let text = "Hello world, welcome to the universe.";
console.log(text.includes("world")); // true

2. startsWith()

Returns true if a string begins with a specified value.

let text = "Hello world";
console.log(text.startsWith("Hello")); // true

3. endsWith()

Returns true if a string ends with a specified value.

let text = "Mim Akter";
console.log(text.endsWith("Akter")); // true
Tip: All these methods are case-sensitive. Searching for "WORLD" is not the same as searching for "world".

Key Points to Remember

  • indexOf() and lastIndexOf() return positions (or -1)
  • includes(), startsWith(), and endsWith() return true or false
  • Positions in JavaScript start from 0
  • All these search methods are case-sensitive
  • Modern ES6 methods (like includes) make code much more readable than indexOf(...) !== -1