JavaScript | string.search()

The string.search() is an inbuilt function in JavaScript which is used to search for a match in between regular expressions and a given string object.

Syntax :

string.search(A)

Parameters: Here parameter “A” is a regular expression object.
Return Value: This function returns the index of the first match in between regular expression and the given string object and returns -1 if no match found.

JavaScript code to show the working of string.search()

Code #1:
Indexing starts from zero (0) and if at first attempt a alphabet is match, then it do not check further simply it return the index of that first matched alphabet.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

0
1
4

Code #2:
Here in below code it can be seen that this function is only returning -1, because no matching found in between regular expression and input string.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

-1
-1
-1
-1


My Personal Notes arrow_drop_up

Image
Check out this Author's contributed articles.

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.