The search() method in JavaScript is used to search for a specified substring or a regular expression pattern within a string. It returns the index of the first match found, or -1 if no match is found.
Syntax: string.search(searchValue)
- searchValue: The substring or regular expression pattern to search for within the string.
Example:
let str = "Hello, World!";
let index = str.search("World");
console.log(index); // Output: 7
Explanation:
- We have a string str containing "Hello, World!".
- We use search("World") to find the index of the first occurrence of "World" within the string.
- The method returns 7 because "World" starts at index 7 in the string.
The search() method provides more flexibility by allowing us to search using regular expressions.
Code Compiler Link: https://app.singhteekam.in/codecompiler/