> For the complete documentation index, see [llms.txt](https://choubey.gitbook.io/javascript-interview-questions/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://choubey.gitbook.io/javascript-interview-questions/question-5.md).

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

  ```javascript
  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)`**&#x20;

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

  ```javascript
  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)`**&#x20;

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

  ```javascript
  const text = "This is a test.";
  const regex = /\btest\b/i; // Matches the word "test" (case-insensitive)

  console.log(text.search(regex)); // Output: 10
  ```
