Question 5

Question

Explain the difference between indexOf(), includes(), and search() methods for string manipulation.

Answer

1. indexOf(searchString, start)

  • Purpose: Finds the first occurrence of a substring (searchString) within a given string.

  • Return Value: Returns the index (position) of the first occurrence of searchString. If not found, it returns -1.

  • start Parameter (optional): Allows you to specify where to start searching within the string.

    const text = "Hello world!";
    console.log(text.indexOf("world")); // Output: 6
    console.log(text.indexOf("hello", 5)); // Output: 6 (searching from index 5)
    console.log(text.indexOf("banana")); // Output: -1 (not found)

2. includes(searchString, start)

  • Purpose: Checks if a string (searchString) exists anywhere within another string.

  • Return Value: Returns true if the substring is found, and false otherwise.

  • start Parameter (optional): Similar to indexOf(), it lets you control the search starting point.

    const text = "Hello world!";
    console.log(text.includes("world"));    // Output: true
    console.log(text.includes("example"));  // Output: false 
    console.log(text.includes("lo", 4));     // Output: true (searching from index 4)

3. search(regexp)

  • Purpose: Searches for a regular expression (regexp) within a string. This method provides the most powerful and flexible pattern matching capabilities.

  • Return Value: Returns the index of the first match found, or -1 if no match is found.

    const text = "This is a test.";
    const regex = /\btest\b/i; // Matches the word "test" (case-insensitive)
    
    console.log(text.search(regex)); // Output: 10

Last updated