Tutorialspoint.dev

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.

<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

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.

<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


This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter