The String search() method

By

Learn how the JavaScript search() method returns the index of the first match of a string or regular expression inside a string, or -1 when there is no match.

~~~

The search() method of a string returns the position of the first occurrence of the string or regular expression you pass to it. It returns the index where the match starts, or -1 if no match is found.

'JavaScript'.search('Script') //4
'JavaScript'.search('TypeScript') //-1

The index starts at 0, so a match at the very beginning of the string returns 0:

'JavaScript'.search('Java') //0

Be careful when you use the result in a condition. 0 is falsy, so if ('JavaScript'.search('Java')) would not run even though the match exists. Compare against -1 instead:

if ('JavaScript'.search('Java') !== -1) {
  //found
}

Searching with a regular expression

You can search using a regular expression, which is where search() earns its place. Patterns and flags work as you’d expect:

'JavaScript'.search(/Script/) //4
'JavaScript'.search(/script/i) //4
'JavaScript'.search(/a+v/) //1

The i flag makes the search case insensitive. The a+v pattern matches one or more a characters followed by a v, and the first place that happens is index 1.

A pitfall: strings become regular expressions

Even if you pass a string, that’s internally and transparently converted to a regular expression. This means characters that are special in regex syntax keep their special meaning:

'a.c'.search('.') //0

You might expect 1, the position of the literal dot. But . in a regular expression matches any character, so the first match is the a at index 0.

To search for the literal character, escape it in a regex:

'a.c'.search(/\./) //1

Or use indexOf(), which treats its argument as plain text:

'a.c'.indexOf('.') //1

Which method should you use?

Use search() when you need the position of a pattern, like “the first digit” or “the first word regardless of case”. If you’re searching for plain text, indexOf() does the same job with no regex surprises. And if you need details about the match itself, the matched text or capture groups, use match() instead: search() only ever gives you the position.

~~~

Related posts about js: