JavaScript | string.search() Method
The string.search() method is the inbuilt method in JavaScript which is used to search for a match in between regular expressions and a given string object.
Syntax:
string.search( A )
Parameters: This method accepts single parameter A which holds the regular expression as object.
Return Value: This function returns the index of the first match string in between regular expression and the given string object and returns -1 if no match found. Indexing starts from zero (0) and in a first attempt, an alphabet is matched, then it does not check further simply it returns the index of that first matched alphabet.
Below examples illustrate the string.search() method in JavaScript:
Example 1:
<script> // Taking input a string. var string = "GeeksforGeeks"; // Taking a regular expression. var re1 = /G/; var re2 = /e/; var re3 = /s/; // Printing the index of matching alphabets document.write(string.search(re1) + "<br>"); document.write(string.search(re2) + "<br>"); document.write(string.search(re3)); < /script> |
Output:
0 1 4
Example 2: This example returns -1, because of no match found in between regular expression and the input string.
<script> // Taking input a string. var string = "GeeksforGeeks"; // Taking a regular expression. var re1 = /p/; var re2 = /1/; var re3 = / /; var re4 = /, /; // Printing the index of matching alphabets document.write(string.search(re1) + "<br>"); document.write(string.search(re2) + "<br>"); document.write(string.search(re3) + "<br>"); document.write(string.search(re4)); < /script> |
Output:
-1 -1 -1 -1
Recommended Posts:
- JavaScript | compile() Method
- JavaScript | Sort() method
- JavaScript | padStart() Method
- JavaScript | Array map() Method
- JavaScript | Replace() Method
- JavaScript | getTime() Method
- JavaScript | Promise.all() Method
- JavaScript | exec() Method
- JavaScript | Array.from() method
- JavaScript | hasOwnProperty() Method
- JavaScript | padEnd() Method
- JavaScript | Array from() Method
- JavaScript method to get the URL without query string
- JavaScript | Array reduce() Method
- JavaScript | array.entries() Method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

