Description

The JavaScript String method search() searches for a match between a given string and a regular expression.

The method is case sensitive, so the case is also considered when it tries to search for a match.

Syntax

The method search() has the below syntax, where str is a string.

str.search(regexp)

Parameters

The method search() allows the below parameters.

regexp

  • It is a regular expression object.
  • If it is a non-RegExp object, then the argument is implicitly converted to a RegExp object.

Result

Returns the index of the first match between the string and a regular expression.

Returns -1 in case of no match.

Example 1: Search Using Regular Expressions

If we need to search for a pattern, use regular expressions to provide a search pattern.

var str = "Hello hello HELLO Hello hello HELLO";
var searchPattern = /hello/;

// Searching for a pattern
document.write(str.search(searchPattern));     // Prints: 6

Output:

6

Example 2: Search Using Plain Text

If we need to search for a text, then use the search text directly instead of a regular expression.

var str = "Hello hello HELLO Hello hello HELLO";
var searchString = "hello";

// Searching for a text
document.write(str.search(searchString));   // Prints: 6

Output:

6

Example 3: Search String Not Found

If the method doesn't find a match, then it returns -1 as shown below.

var str = "Hello hello HELLO Hello hello HELLO";
var searchString = "world";
var searchPattern = /world/;

// Searching for a text
document.write(str.search(searchString));     // Prints: -1

// Searching for a pattern
document.write(str.search(searchPattern));     // Prints: -1

Output:

-1
-1

Example 4: Search with Ignoring Case

By default, the method is case-sensitive, so the search considers the case as well.

If we want to perform a case-insensitive search, then we need to use a regex with i a switch for a case-insensitive search.

var str = "Hello hello HELLO Hello hello HELLO";
var pattern = /hello/;
var patternCaseInsensitive = /hello/i;

// Searching for a text
document.write(str.search(pattern));     // Prints: 6

// Searching for a pattern
document.write(str.search(patternCaseInsensitive));     // Prints: 0

Output:

6
0

Overall

The JavaScript String method search() searches for a match between a given string and a regular expression.

Related Links