JavaScript Reference ยท String
String.prototype.search()
Reference for JavaScript String.prototype.search(): get the index of the first regular expression match, or -1, and how it differs from indexOf() and match().
The search() method looks for the first match of a regular expression in a string and returns its index, or -1 if there is no match. It is the regular-expression counterpart of indexOf().
You get only the position, not the matched text. If you need the text or capture groups, use match(). If you only need a yes or no answer, regex.test(string) is usually the clearest choice.
"Hello, world".search(/o/); // 4
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
string.search(regexp)
| Name | Description |
|---|---|
regexp |
A regular expression, or an object with a Symbol.search method. Any other value is converted with new RegExp(value). If omitted, it behaves like an empty pattern. |
Return value: the zero-based index of the first match, or -1 if nothing matches.
Exceptions: a SyntaxError if a string argument is not a valid regular expression, for example "(".
Usage notes
- A string is not literal here.
"a.b".search(".")returns0, because"."becomes the pattern/./. For literal text useindexOf(), or escape the string. - Flags
gandyare ignored, and the regular expression'slastIndexis neither used nor changed. The search always starts at index0, andlastIndexis restored afterward. - Only the first match is found. To find all matches, use
matchAll(). - No start position. Unlike
indexOf(), you cannot tellsearch()where to begin. Slice the string first, or use a sticky regular expression withexec(). - Boolean checks:
str.search(re) !== -1works, butre.test(str)is shorter, as long as you avoid statefulgoryregular expressions withtest(). - Index units are UTF-16 code units, like every string index in JavaScript.
- Empty pattern:
"abc".search("")returns0, and a missing argument also returns0.
Browser support
String.prototype.search() has been available in every browser for a very long time.