Javascript string.search() method is the inbuilt method in JavaScript that is used to search for a match between regular expressions and a given string object, basically string.search() method used to find the index (position) of the first match and we can use it as a case sensitive
Syntax:
string.search( A )
Parameters: This method accepts a single parameter A which holds the regular expression as an object.
Return Value:
- This method 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
// Taking input a string. let string = "neveropen" ; // Taking a regular expression. let re1 = /G/; let re2 = /e/; let re3 = /s/; // Printing the index of matching alphabets console.log(string.search(re1)); console.log(string.search(re2)); console.log(string.search(re3)); |
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
// Taking input a string. let string = "neveropen" ; // Taking a regular expression. let re1 = /p/; let re2 = /1/; let re3 = / /; let 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)); |
Output:
-1
-1
-1
-1
Example: In this example, we are using the search() method without using regular expressions. The search() method is used to find the index of the substring “for” in the string “neveropen”.
Javascript
let str = "neveropen" ; let searchString = "for" ; let Result = str.search(searchString); console.log(Result); |
5
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