Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

String.prototype.search — find a pattern's match index

The search() method finds the first regular-expression match and returns its index or -1. A string argument is interpreted as a pattern, not as a literal substring.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

string.search(regexp)

String.prototype.search returns the index of the first match for an ordinary RegExp, or -1 if there is no match. The index is zero-based and measured in UTF-16 code units, not visible characters. The method does not change the string or return the matched substring. Test the result with !== -1: index 0 is a successful match.

If the argument has a callable [Symbol.search] method, whether own or inherited, search() calls it instead of creating a new regular expression. Ordinary RegExp instances inherit this method from RegExp.prototype. If the argument is null or undefined, or looking up its [Symbol.search] property yields null or undefined, search() creates a regular expression from the argument. Any other non-callable value for that property throws a TypeError. Consequently, "abc".search(".") returns 0: . matches any character except a line terminator, not a literal dot. Use indexOf() for literal text searches. Omitting the argument or passing undefined creates an empty pattern and produces 0.

For an ordinary RegExp, the g flag does not collect all matches. Searching starts with lastIndex set to 0, and its previous value is restored after normal completion. The y flag still requires a match at the start of the string. The method accepts no starting-position argument.

A custom [Symbol.search] method can define the behavior completely, including the result type. In the example, the digits start at index 7, lastIndex stays 8, and a missing match produces -1.

Examples

const text = "Order: 42";
const pattern = /\d+/g;
pattern.lastIndex = 8;

console.log(text.search(pattern));
console.log(pattern.lastIndex);
console.log(text.search(/missing/));
console.log("abc".search("."));

Result

7
8
-1
0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources