JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS String Search


Searching within strings is a common requirement in JavaScript, whether you are validating input, finding keywords, or processing text data. JavaScript provides several string methods to search for substrings, locate characters, or match patterns using regular expressions. Understanding these methods allows developers to efficiently manipulate and analyze text content.

In this chapter, you will learn about the different string search methods, practical examples using real-world scenarios, common mistakes, best practices, and applications of string search in JavaScript.

Why String Search Is Important

String search is essential for:

  • Validating user input (emails, names, codes)

  • Finding keywords or phrases in text

  • Highlighting or filtering content dynamically

  • Parsing or extracting information from data

  • Implementing search functionality in applications

Without effective string search, working with text-based data becomes inefficient and error-prone.

Common String Search Methods

1. indexOf()

The indexOf() method searches for a substring and returns the index of the first occurrence. If the substring is not found, it returns -1.

let message = "Riya submitted her assignment";
console.log(message.indexOf("Riya")); // 0
console.log(message.indexOf("Ananya")); // -1

You can also provide a second argument to specify the starting index for the search:

let text = "Mira and Mira are friends";
console.log(text.indexOf("Mira", 5)); // 9

2. lastIndexOf()

lastIndexOf() returns the index of the last occurrence of a substring.

let text = "Ananya and Ananya are classmates";
console.log(text.lastIndexOf("Ananya")); // 12

3. search()

The search() method searches for a match using a regular expression and returns the index of the first match. Returns -1 if not found.

let text = "Diya is learning JavaScript";
console.log(text.search("Diya")); // 0

// Using regular expression
console.log(text.search(/JavaScript/i)); // 17

Unlike indexOf(), search() can handle complex patterns using regular expressions.

4. includes()

includes() checks if a substring exists in a string and returns true or false.

let student = "Mira Gupta";
console.log(student.includes("Mira")); // true
console.log(student.includes("Diya")); // false

5. startsWith() and endsWith()

These methods check if a string starts or ends with a specified substring.

let student = "Sneha Sharma";

console.log(student.startsWith("Sneha")); // true
console.log(student.endsWith("Sharma"));  // true
console.log(student.startsWith("Sharma")); // false

These methods are useful for prefix or suffix validation, such as checking file extensions or titles.

6. Using Regular Expressions with match()

The match() method retrieves matches using a regular expression. It can return the first match or all matches depending on the g flag.

let text = "Ananya, Riya, Mira, Diya";
let result = text.match(/a/gi); // Finds all occurrences of 'a'
console.log(result); // ["a","a","a","a","a","a"]

Practical Examples

Example 1: Keyword Search in Text

let article = "Diya is learning JavaScript basics";
if (article.includes("JavaScript")) {
    console.log("The article contains JavaScript.");
}

Example 2: Finding All Occurrences of a Letter

let names = "Ananya, Mira, Riya, Diya";
let letterA = names.match(/a/gi);
console.log(`Letter "a" occurs ${letterA.length} times.`);

Example 3: Validating File Names

let fileName = "assignment.docx";
if (fileName.endsWith(".docx")) {
    console.log("Valid document file.");
} else {
    console.log("Invalid file type.");
}

Example 4: Searching Multiple Words Using Regex

let message = "Riya, Mira, and Ananya are in the class.";
let pattern = /Riya|Mira/gi;
let found = message.match(pattern);
console.log(found); // ["Riya", "Mira"]

Example 5: Checking String Start

let greeting = "Hello, Diya!";
if (greeting.startsWith("Hello")) {
    console.log("Greeting starts correctly.");
}

Common Mistakes

  • Using indexOf() when a boolean result is sufficient (use includes() instead)

  • Ignoring case sensitivity in search operations

  • Not using the g flag when multiple matches are required with regex

  • Confusing search() and match(); they return different types of results

  • Using negative indices incorrectly with indexOf() or lastIndexOf()

Best Practices

  • Use includes() for simple presence checks

  • Use search() or match() when working with patterns

  • Normalize case using toLowerCase() or toUpperCase() before searching if needed

  • Validate strings before performing search operations

  • Combine string search with conditional logic for dynamic applications

Real-World Applications

String search methods are widely used in:

  • Search bars and filtering lists

  • Form validation and input checks

  • Highlighting keywords in articles or messages

  • Detecting specific patterns in data

  • File type validation and processing

  • Text parsing and data extraction

Summary of JS String Search

JavaScript string search methods provide powerful tools to locate, match, and validate text. Methods such as indexOf(), search(), includes(), startsWith(), endsWith(), and match() allow developers to handle simple and complex search tasks efficiently. Mastering these methods helps in building interactive applications, validating inputs, and processing text data reliably.


Practice Questions

Q1. How do you find the position of the first occurrence of "o" in "hello world"?

Q2. How do you find the index of the last "l" in "hello"?

Q3. Which method would you use to check if "apple" starts with "ap"?

Q4. How do you test if the string "coding" includes the substring "ing"?

Q5. How do you check if a string ends with "!"?

Q6. What does "banana".indexOf("na") return?

Q7. What does "banana".lastIndexOf("na") return?

Q8. How do you search for "e" using a regular expression in the string "elephant"?

Q9. How do you confirm if the word "JavaScript" includes the word "Script"?

Q10. How do you check whether "Hello" starts with "H" and ends with "o"?


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top