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 Search Methods
In JavaScript, a regular expression text search, can be done with different methods.
With a pattern as a regular expression, these are the most common methods:
Example | Description |
---|---|
text.match(pattern) | The String method match() |
text.search(pattern) | The String method search() |
pattern.exec(text) | The RexExp method exec() |
pattern.test(text) | The RegExp method test() |
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 |