JavaScript tutorial:
search method

 

Applies to: String Object

The search method returns the position of the first substring match in a regular expression search.

Syntax

stringObj.search(rgexp)

The search method syntax has these parts:

Part

Description

stringObj

Required. The String object or literal to search.

rgexp

Required. A Regular Expression object containing the pattern to search for.

Return value

The search method returns the position of the first substring match in a regular expression search.

Example

The search method indicates if a match is present or not. If a match is found, the search method returns an integer value that indicates the offset from the beginning of the string where the match occurred. If no match is found, it returns -1. To get further information, use the match method.

The following example illustrates the use of the search method:

function searchString(s, re)
{
var r = s.search(re);
return(r);
}
document.write(searchString("Helle world java script is fun",/java script/i ));

  To run the code, paste it into JavaScript Editor, and click the Execute button.