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 »
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.
** If the search value is a string, it is converted to a regular expression.
string.search(
searchValue)
Parameter | Description |
searchValue | Required. The search value. A regular expression (or a string that will be converted to a regular expression). |
Type | Description |
A number | The position of the first match. -1 if no match. |
The search()
cannot take a start position argument.
The indexOf()
method cannot search against a regular expression.
The search()
method returns the position of the first match.
The match()
method returns an array of matches.
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() |
search()
is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!