HTML and CSS Reference
In-Depth Information
EXAMPLE
17.27
<html>
<head><title>Beginning of Line Anchor</title></head>
<body>
<script type="text/javascript">
1
var reg_expression = /^[JK]/;
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 /^[JK]/ matched
the string\""+ textString +"\".<br />");
}
else{
alert("No Match!");
}
</script>
</body>
</html>
EXPLANATION
1
A regular expression contains a beginning of line anchor, the caret. The regular
expression reads: Find either an uppercase
J
or uppercase
K
at the beginning of
the line or string.
2
The variable
textString
is assigned user input; in this example,
Jack and Jill
.
3
The regular expression
test()
method will return
true
because the string
Jack
matches an uppercase letter
J
and is found at the beginning of the string. See
Figure 17.29.
Figure 17.29
The string must begin with either a
J
or
K
. The user entered
Jack and
Jill
(top) and this returns
true
; the user entered
Karen Evich
(bottom) and this also
returns
true
.