HTML and CSS Reference
In-Depth Information
EXAMPLE
17.11
<html>
<head><title>The dot Metacharacter</title></head>
<body>
<script type="text/javascript">
1
var textString="Norma Jean";
2
var reg_expression = /N..ma/;
3
var result=reg_expression.test(textString); //
Returns true
//
or false
document.write(result+"<br />");
4
if (
reg_expression.test(textString))
{ // if (
result)
document.write("<b>The reg_ex /N..ma/ matched the
string\""+ textString +"\".<br />");
}
else{
5
document.write("No Match!");
}
</script>
</body>
</html>
EXPLANATION
1
The variable
textString
is assigned the string
“Norma Jean”
.
2
The regular expression
/N..ma/
is assigned to the variable
reg_expression
. A match
is found if the string being tested contains an uppercase
N
followed by any two
single characters (each dot represents one character), and an
m
and an
a
. It would
find
Norma
,
No man
,
Normandy
, and so on.
3
The
test
method returns
true
if the string
textString
matches the regular expression
and
false
if it doesn't. The variable
result
contains either
true
or
false
.
4
If the string
“Norma Jean”
contains regular expression pattern
/N..ma/
, the return
from the
test
method is true, and the output is sent to the screen as shown in
Figure 17.11.
5
If the pattern is not found,
No Match!
is displayed on the page.
Figure 17.11
The user entered
Norma Jean
,an
N
followed by any 2 characters,
and
ma.