String.prototype.search()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Thesearch() method ofString values executes a search for a match between a regular expression and this string, returning the index of the first match in the string.
In this article
Try it
const paragraph = "I think Ruth's dog is cuter than your dog!";// Anything not a word character, whitespace or apostropheconst regex = /[^\w\s']/g;console.log(paragraph.search(regex));// Expected output: 41console.log(paragraph[paragraph.search(regex)]);// Expected output: "!"Syntax
search(regexp)Parameters
regexpA regular expression object, or any object that has a
Symbol.searchmethod.If
regexpis not aRegExpobject and does not have aSymbol.searchmethod, it is implicitly converted to aRegExpby usingnew RegExp(regexp).
Return value
The index of the first match between the regular expression and the given string, or-1 if no match was found.
Description
The implementation ofString.prototype.search() doesn't do much other than calling theSymbol.search method of the argument with the string as the first parameter. The actual implementation comes fromRegExp.prototype[Symbol.search]().
Theg flag ofregexp has no effect on thesearch() result, and the search always happens as if the regex'slastIndex is 0. For more information on the behavior ofsearch(), seeRegExp.prototype[Symbol.search]().
When you want to know whether a pattern is found, andalso know its index within a string, usesearch().
- If you only want to know if it exists, use the
RegExp.prototype.test()method, which returns a boolean. - If you need the content of the matched text, use
String.prototype.match()orRegExp.prototype.exec().
Examples
>Using search()
The following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1).
const str = "hey JudE";const re = /[A-Z]/;const reDot = /[.]/;console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"console.log(str.search(reDot)); // returns -1 cannot find '.' dot punctuationSpecifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-string.prototype.search> |