Skip to main content

search() JavaScript String Method – How to Search a String

Whenever you use search() on a string, the method does the following:

  1. It searches its calling string for the method's regular expression argument.
  2. It returns the index position of the first match, or -1 if the RegExp pattern found no match.
note

A calling string is a string on which you used search(). So, in "Hello, world!".search("world"), "Hello, world!" is the calling string.

Syntax of the search() Method

search() accepts a regular expression argument. Here is the syntax:

callingString.search(RegExp);
note
  • Suppose search()'s argument is a non-RegExp value—such as a string or a number. In that case, JavaScript will use the new RegExp(...) syntax to convert the argument to a regular expression.
  • 0 returns if you do not provide an argument.

Example 1: Search for day

"SunDay, Tuesday, and Friday are good DAYS".search(/day/);

// The invocation above will return: 12

Try it on StackBlitz

Example 2: Search for a Case-Insensitive day Pattern

"SunDay, Tuesday, and Friday are good DAYS".search(/day/i);

// The invocation above will return: 3

Try it on StackBlitz

tip
  • Suppose you need to start your search from a specific index position. In that case, use indexOf().
  • To do a global search for all matches, use match().

Overview

search() searches its calling string for the first occurrence of the method's regular expression argument.