HTML and CSS Reference
In-Depth Information
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
page 733.)
FORMAT
var index_value = String.search(regular_expression);
EXAMPLE
var position = "A needle in a haystack".
search(/needle/
);
EXAMPLE
17.6
<html>
<head>
<title>The search() Method</title>
</head>
<body bgcolor="yellow">
<big>
<font face="arial, helvetica">
<script type="text/javascript">
1
var myString="I love the smell of clover."
2
var regex = /love/;
3
var index=myString.search(regex);
document.write("Found the pattern "+ regex+ " at position "
+index+"<br />");
</script>
</font></big>
</body>
</html>
EXPLANATION
1
The variable called
myString
is assigned the string,
“I love the smell of clover.”
2
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.
3
The
String
object's
search()
method returns the index position, starting at zero,
where the regular expression,
regex
, is found. See Figure 17.7.