HTML and CSS Reference
In-Depth Information
EXAMPLE
17.26 (
CONTINUED
)
<script type="text/javascript">
1
var reg_expression = /^Will/;
//
Beginning of line anchor
2
var textString=prompt("Type a string of text","");
3
var result=reg_expression.test(textString)
;//
Returns true
//
or false
document.write(result+"<br />");
if (result){
document.write("<b>The regular expression /^Will/ matched
the string\""+ textString +"\".<br />");
}
else{
alert("No Match!");
}
</script>
</body>
</html>
EXPLANATION
1
The variable is assigned a regular expression containing the beginning of line an-
chor metacharacter, the caret, followed by
Will
.
2
The variable
textString
is assigned user input; in this example,
Willie Wonker
was
entered.
3
The regular expression
test()
method will return
true
because the string
Willie
Wonker
begins with
Will
. See Figure 17.28.
Figure 17.28
The user entered
Willie Wonker
.
Will
is at the beginning of the line, so
this tests true (top); if the user enters
I know Willie
, and
Will
is not at the beginning of
the line, the input would test
false
(bottom).