Javascript - String search() Method

The search() method searches a string for a specified value, and returns the matched position.

Description

The search() method searches a string for a specified value, and returns the matched position.

The search value can be string or a regular expression.

This method returns -1 if no match is found.

Syntax

string.search(searchvalue)

Parameter Values

Parameter RequireDescription
searchvalue Required. A regular expression. A string will automatically be converted to a regular expression.

Return

A Number, representing the position of the first occurrence of the specified searchvalue, or -1 if no match is found

Example

Search for "W":

Demo

//search a string for "t", and display the position of the match.
var str = "this is a test";
var n = str.search("t");
console.log(n);//from w w  w .j  av  a2  s  .  c  om

//Perform a case-sensitive search:
//search a string for "blue", and display the position of the match.
var str = "this is Blue blue"
var n = str.search("blue");
console.log(n);

//Perform a case-insensitive search:
//search a string for "blue", and display the position of the match.
var str = "Blue blue"
var n = str.search(/blue/i);
console.log(n);

Result