JavaScriptStrings

String.prototype.search()

Returns the index of the first match of a regular expression in a string, or -1.

Returns
The index of the first match, or -1 when the pattern does not match anywhere.
Changes the original
No
On this page

Example

#
JavaScript
const code = 'Discount code: CODE2026'

console.log(code.search(/\d/))
console.log(code.search(/[A-Z]{4}/))
console.log(code.search(/python/i))
Console
19
15
-1

Definition and usage

#

The search() method checks a string against a regular expression and returns the position where the first match starts. When the pattern does not match anywhere, the result is -1. So it works like indexOf(), but it searches for a pattern instead of fixed text.

That lets you find the first digit in a text, the first uppercase letter, or a word written in any letter case (the i flag). If you pass a plain string, it gets converted to a regular expression, so characters like . or ? keep their special meaning.

The method always searches from the start of the string and ignores the g flag and the lastIndex property. When you need the matched text itself, use match(), and for a simple matches-or-not answer, regex.test(text) is enough.

Syntax

#
Syntax
string.search(regexp)

Parameters

#
  • regexp

    RegExp | string

    A regular expression. A plain string gets converted to one via new RegExp().

More examples

#
search() versus indexOf()
JavaScript
const title = 'Lesson 12: Loops'

console.log(title.indexOf('12'))
console.log(title.search(/\d+/))
console.log(title.indexOf('.'))
console.log(title.search('.'))
Console
7
7
-1
0

There is no period in the title, yet search(".") still returned 0. The string turned into a regular expression, where a dot means any character.

Extracting a postal code
JavaScript
const address = '42 Flower Street, 00-950 Springfield'
const start = address.search(/\d{2}-\d{3}/)

console.log(start)
console.log(address.slice(start, start + 6))
Console
18
00-950

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • A string you pass in becomes a regular expression, so "1.5".search(".") returns 0, because a dot matches any character. Use indexOf() to search for fixed text.
  • A result of 0 means a match right at the start, not the absence of one. Compare the result against -1.

Related entries

#

Spotted a mistake or missing an example? Write to us.