search (String - JavaScript)

Gets the index of the first occurrence of a substring.

Defined in

String (Standard - JavaScript)

Syntax

search(searchValue:string) : int

search(searchValue:RegExp) : int

Parameters Description
searchValue A string or regular expression.
Return value Description
int The index of the first occurrence of the string or regular expression, or -1 if the search fails.

Usage

If the first parameter is a string, this method finds the first string that matches exactly. If the first parameter is a regular expression, this method finds the first string that matches according to the syntax of the regular expression.

Examples

(1) This example searches for the string moscow case-insensitive.
var cities = new String("Paris   Moscow   Tokyo");
var regexp = /(moscow)/i;
if (cities.search(regexp) > 0) {
	return "Found: " + regexp.toString();
} else {
	return "Not found: " + regexp.toString();
}
(2) This example searches for the string Moscow.
var cities = new String("Paris   Moscow   Tokyo");
if (cities.search("Moscow") > 0) {
	return "Found: Moscow";
} else {
	return "Not found: Moscow";
}