String.prototype.search
Executes a search for a match between a regular expression and this string, returning the index of the first match
Syntax
string.search(regexp)Parameters
| Parameter | Type | Description |
|---|---|---|
| regexp | RegExp | A regular expression object |
Return Value
The index of the first match, or -1 if no match
Examples
const str = 'Hey! Look at that.';
console.log(str.search(/[!]/)); // 3const text = 'no numbers here... wait 42!';
console.log(text.search(/\d+/)); // 24const str = 'Hello World';
console.log(str.search(/world/i)); // 6Understanding String.prototype.search
The String.prototype.search method in JavaScript executes a search for a match between a regular expression and this string, returning the index of the first match. It belongs to the String object and is one of the most widely used methods for working with string values in modern JavaScript and TypeScript applications.
The method signature is string.search(regexp). It accepts 1 parameter: regexp. When called, it returns the index of the first match, or -1 if no match. Understanding when and how to use search() helps you write more expressive, readable code.
Common use cases for String.prototype.search include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like string-match, string-indexof, string-includes, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for String.prototype.search is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
String.prototype.matchRetrieves the result of matching a string against a regular expression
String.prototype.indexOfReturns the index of the first occurrence of a specified value in a string, or -1 if not found
String.prototype.includesDetermines whether one string may be found within another string, returning true or false
RegExp.prototype.testExecutes a search for a match between a regular expression and a specified string, returning true or false
More String Methods
Other methods in the String object
Related Tools
More String Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.