JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript String Search

8 April 2025 | Category:

In JavaScript, you often need to search for a specific word or pattern inside a string. JavaScript provides several methods to help you find, locate, or match parts of a string easily.


✅ Why Use String Search Methods?

Whether you’re checking if a word exists in a sentence, finding the position of a character, or matching a pattern using regular expressions, JavaScript’s string search tools have you covered.


🔹 1. indexOf() – Finds the first occurrence

let text = "I love JavaScript!";
console.log(text.indexOf("JavaScript")); // Output: 7
  • Returns the index of the first match.
  • Returns -1 if the text is not found.

🔹 2. lastIndexOf() – Finds the last occurrence

let text = "I love JavaScript. JavaScript is fun!";
console.log(text.lastIndexOf("JavaScript")); // Output: 18
  • Useful when a word appears multiple times.

🔹 3. search() – Searches using a regular expression

let text = "I love JavaScript!";
console.log(text.search(/script/i)); // Output: 10
  • i makes the search case-insensitive.
  • Similar to indexOf, but more powerful with regex.

🔹 4. includes() – Checks if a string contains a value

let text = "Hello world!";
console.log(text.includes("world")); // Output: true
  • Returns a boolean (true or false).
  • Case-sensitive.

🔹 5. startsWith() – Checks if string starts with given value

let text = "JavaScript is awesome!";
console.log(text.startsWith("Java")); // Output: true
  • You can also pass a start position as the second argument.

🔹 6. endsWith() – Checks if string ends with given value

let text = "Learn JavaScript";
console.log(text.endsWith("Script")); // Output: true
  • Can also be used with a length argument to test within a portion of the string.

✨ Bonus: Using Regular Expressions with match()

let text = "The rain in Spain";
let result = text.match(/ain/g); 
console.log(result); // Output: ["ain", "ain"]
  • match() finds all matches of a pattern.
  • g is the global flag (find all, not just the first).

🧠 Summary Table

MethodDescriptionReturns
indexOf()First position of a matchNumber (-1 if not found)
lastIndexOf()Last position of a matchNumber
search()Search using regexNumber
includes()Checks if string contains valueBoolean
startsWith()Checks beginning of stringBoolean
endsWith()Checks end of stringBoolean
match()Finds matches using regexArray or null