String.prototype.search()

search(regexp)
Returns: number · Updated March 13, 2026 · String Methods
string regex search regexp

The search() method searches a string for a specified pattern and returns the index of the first match. If no match is found, it returns -1. Unlike indexOf(), search() accepts regular expressions, enabling complex pattern matching including wildcards, character classes, and quantifiers.

Syntax

string.search(regexp)

Parameters

ParameterTypeDefaultDescription
regexpRegExp | stringThe pattern to search for. If a string is passed, it’s converted to a RegExp internally.

Examples

Basic usage with a string

const text = "Hello, world! Welcome to JavaScript.";
const index = text.search("world");
console.log(index);
// 7

Using a regular expression

const text = "The price is $19.99 and the discount is $5.00";
const index = text.search(/\$\d+\.\d{2}/);
console.log(index);
// 12
const text = "JavaScript is FUN";
const index = text.search(/javascript/i);
console.log(index);
// 0

Finding the position of a word boundary

const text = "The cat sat on the mat";
const index = text.search(/\bcat\b/);
console.log(index);
// 4

When pattern is not found

const text = "Hello, world!";
const index = text.search("python");
console.log(index);
// -1

Common Patterns

A common use case is validating whether a string contains a certain pattern before processing:

function containsEmail(text) {
  const emailPattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;
  return text.search(emailPattern) !== -1;
}

console.log(containsEmail("Contact me at john@example.com"));
// true
console.log(containsEmail("No email here"));
// false

Combine with other string methods

You can use search() to check if a pattern exists, then use other methods like replace() or slice():

const text = "Product ID: ABC-12345";
const prefix = "Product ID: ";

if (text.search(prefix) !== -1) {
  const id = text.slice(text.search(prefix) + prefix.length);
  console.log(id);
// ABC-12345
}

See Also