The Wayback Machine - https://web.archive.org/web/20211125094331/https://www.geeksforgeeks.org/javascript-string-search/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

JavaScript string.search() Method

  • Last Updated : 18 Nov, 2021

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

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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 regular expression and the given string object and returns -1 if no match is 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.



Example 1: The below example illustrate 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
  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.

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

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
Recommended Articles
Page :