String

String.prototype.search

Executes a search for a match between a regular expression and this string, returning the index of the first match

Syntax

JavaScript
string.search(regexp)

Parameters

ParameterTypeDescription
regexpRegExpA regular expression object

Return Value

The index of the first match, or -1 if no match

Examples

Basic Usage
const str = 'Hey! Look at that.';
console.log(str.search(/[!]/)); // 3
Practical Example
const text = 'no numbers here... wait 42!';
console.log(text.search(/\d+/)); // 24
Advanced Usage
const str = 'Hello World';
console.log(str.search(/world/i)); // 6

Understanding 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

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.