JavaScript String search()
Examples
Search for "Blue":
let text = "Mr. Blue has a blue house";
let position = text.search("Blue");
Try it Yourself »
Search for "blue":
let text = "Mr. Blue has a blue house";
let position = text.search("blue");
Try it Yourself »
Search for /Blue/:
let text = "Mr. Blue has a blue house";
let position = text.search(/Blue/);
Try it Yourself »
Search for /blue/:
let text = "Mr. Blue has a blue house";
let position = text.search(/blue/);
Try it Yourself »
Search case insensitive:
let text = "Mr. Blue has a blue house";
let position = text.search(/blue/i);
Try it Yourself »
Description
The search()
method matches a string against a regular expression **
The search()
method returns the index (position) of the first match.
The search()
method returns -1 if no match is found.
The search()
method is case sensitive.
Note
** If the search value is a string, it is converted to a regular expression.
See Also:
Syntax
string.search(searchValue)
Parameters
Parameter | Description |
searchValue | Required. The search value. A regular expression (or a string that will be converted to a regular expression). |
Return Value
Type | Description |
A number | The position of the first match. -1 if no match. |
The Difference Between
String search() and String indexOf()
The search()
cannot take a start position argument.
The indexOf()
method cannot search against a regular expression.
The Difference Between
String search() and String match()
The search()
method returns the position of the first match.
The match()
method returns an array of matches.
Regular Expression Methods
Regular Expression Search and Replace can be done with different methods.
These are the most common:
String Methods
Method | Description |
---|---|
match(regex) | Returns an Array of results |
matchAll(regex) | Returns an Iterator of results |
replace(regex) | Returns a new String |
replaceAll(regex) | Returns a new String |
search(regex) | Returns the index of the first match |
split(regex) | Returns an Array of results |
RegExp Methods
Method | Description |
---|---|
regex.exec() | Returns an Iterator of results |
regex.test() | Returns true or false |
Browser Support
search()
is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |