The search() method searches for a match between a given string and a regular expression.
Example
search() Syntax
The syntax of the search() method is:
str.search(regexp)
Here, str is a string.
search() Parameters
The search() method takes a single parameter:
regExp- A regular expression object (Argument is implicitly converted toregExpif it is a non-regExpobject)
search() Return Value
- Returns the index of the first match between the regular expression and the given string
- Returns -1 if no match was found.
Example 1: Using search() Method
Output
11
In the above example, we have used the search() method to search for a match between the regular expression and the given string.
Here regExp indicates a pattern having 'JavaScript' followed by a digit.
string1.search(regExp) executes the search and returns 11 which is the index value of the match found i.e.'JavaScript1'.
Example 2: Passing non-regExp in search()
Output
10
In the above example, we have passed a non-regular expression 'code' in the search() method.
The method converts 'code' into regExp implicitly and performs a search in the given string.
string1.search("code") returns 10 which is the index of 'code'.
Recommended Reading: JavaScript String match()