Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
"Hello, world".search(/o/); // 4

Try it

JS Finding positions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Strings become regular expressions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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(".") returns 0, because "." becomes the pattern /./. For literal text use indexOf(), or escape the string.
  • Flags g and y are ignored, and the regular expression's lastIndex is neither used nor changed. The search always starts at index 0, and lastIndex is restored afterward.
  • Only the first match is found. To find all matches, use matchAll().
  • No start position. Unlike indexOf(), you cannot tell search() where to begin. Slice the string first, or use a sticky regular expression with exec().
  • Boolean checks: str.search(re) !== -1 works, but re.test(str) is shorter, as long as you avoid stateful g or y regular expressions with test().
  • Index units are UTF-16 code units, like every string index in JavaScript.
  • Empty pattern: "abc".search("") returns 0, and a missing argument also returns 0.

Browser support

String.prototype.search() has been available in every browser for a very long time.