HTML and CSS Reference
The search() method is used to search for a pattern of characters within a string, and
returns the index position of where the pattern was found in the string. The index starts
at zero. If the pattern is not found, -1 is returned. For basic searches, the String object's
indexOf() method works fine, but if you want more complex pattern matches, the
search() method is used, allowing you to use regular expression metacharacters to fur-
ther control the expression. (See the section “Getting Control—The Metacharacters” on
var index_value = String.search(regular_expression);
var position = "A needle in a haystack". search(/needle/ );
<title>The search() Method</title>
<font face="arial, helvetica">
var myString="I love the smell of clover."
var regex = /love/;
document.write("Found the pattern "+ regex+ " at position "
The variable called myString is assigned the string, “I love the smell of clover.”
The variable called regex is assigned the regular expression /love/ . With the
search() method, using the g modifier is irrelevant. The index position of the pat-
tern where it is first found in the string, is returned.
The String object's search() method returns the index position, starting at zero,
where the regular expression, regex , is found. See Figure 17.7.