HTML and CSS Reference
In-Depth Information
EXAMPLE
17.28
<html>
<head><title>End of Line Anchor</title></head>
<body>
<script type="text/javascript">
1
var reg_expression = /50$/;
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 /50$/ matched
the string\""+ textString +"\".<br />");
}
else{
alert("No Match!");
}
</script>
</body>
</html>
EXPLANATION
1
The regular expression
/50$/
is assigned to the variable. The pattern contains the
dollar sign (
$
) metacharacter, representing the end of line anchor only when the
$
is the last character in the pattern. The expression reads: Find a
5
and a
0
fol-
lowed by a newline.
2
The user is prompted for a string of text.
3
If the string ends in 50, the regex test method returns
true
; otherwise
false
.
EXAMPLE
17.29
<html>
<head><title>Anchors</title></head>
<body>
<script type="text/javascript">
1
var reg_expression = /^[A-Z][a-z]+\s\d$/;
//
At the beginning of the string, find one uppercase
//
letter, followed by one or more lowercase letters,
// a space,
and one digit.
2
var string=prompt("Enter a name and a number","");
3
if ( reg_expression.test(string)){
alert("It Matched!!");
}
Continues