Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript string.search() Method

Improve Article
Save Article
Like Article
  • Last Updated : 22 Dec, 2022
Improve Article
Save Article
Like Article

The Javascript string.search() method is the inbuilt method in JavaScript that is used to search for a match in between regular expressions and a given string object.

Syntax:

string.search( A )

Parameters: This method accepts a single parameter A which holds the regular expression as an object.

Return Value: This function returns the index of the first match string in between the regular expression and the given string object and returns -1 if no match is found. Indexing starts from zero (0) and in the first attempt, an alphabet is matched, then it does not check further. Simply, it returns the index of that first matched alphabet.

Example 1: The below example illustrates the string.search() method in JavaScript.

Javascript




<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
    console.log(string.search(re1));
    console.log(string.search(re2));
    console.log(string.search(re3));
</script>

Output:

0
1
4

Example 2: This example returns -1, because of no match was found in between the regular expression and the input string.

Javascript




<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
    console.log(string.search(re1));
    console.log(string.search(re2));
    console.log(string.search(re3));
    console.log(string.search(re4));
</script>

Output:

-1
-1
-1
-1

We have a complete list of Javascript Strings methods, to check those please go through Javascript String Complete reference article.

Supported Browser:

  • Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Internet Explorer 4 and above
  • Opera 4 and above
  • Safari 1 and above

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!