JavaScript String search() Method

JavaScript String search()

Definition and Usage

The search() method matches a string against a regular expression **

The search() method returns the index (position) of the first match.

The search() method returns -1 if no match is found.

The search() method is case sensitive.

Note

** If the search value is a string, it is converted to a regular expression.

See Also:

  • String Search
  • Regular Expression Tutorial
  • Regular Expression Reference

Syntax

string.search(searchValue)

Parameters

Parameter
Description

searchValueRequired.
The search value.
A regular expression (or a string that will be converted to a regular expression).

Return Value

Type
Description

A numberThe position of the first match.
-1 if no match.

The Difference Between
String search() and String indexOf()

The search() cannot take a start position argument.

The indexOf() method cannot search against a regular expression.

The Difference Between
String search() and String match()

The search() method returns the position of the first match.

The match() method returns an array of matches.

Regular Expression Search Methods

In JavaScript, a regular expression text search, can be done with different methods.

With a pattern as a regular expression, these are the most common methods:

Browser Support

search() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome
IE
Edge
Firefox
Safari
Opera

Yes
Yes
Yes
Yes
Yes
Yes