search() JavaScript String Method – How to Search a String
Whenever you use search() on a string, the method does the following:
- It searches its calling string for the method’s regular expression argument.
- It returns the index of the first match, or
-1
if the RegExp pattern found no match.
Syntax of the search()
Method
search()
accepts a regular expression argument. Here is the syntax:
callingString.search(RegExp);
Example 1: Search for day
"SunDay, Tuesday, and Friday are good DAYS".search(/day/);
// The invocation above will return: 12
Example 2: Search for a Case-Insensitive day
Pattern
"SunDay, Tuesday, and Friday are good DAYS".search(/day/i);
// The invocation above will return: 3