HTML and CSS Reference
In-Depth Information
EXAMPLE
17.17
<html>
<head><title>Word and Space Metasymbols</title></head>
<body>
<script type="text/javascript">
1
var reg_expression = /\w\s\w\W/;
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 /\\w\\s\\w\\W/
matched the string\""+ textString +"\".<br />");
}
else{
alert("No Match!");
}
</script>
</body>
</html>
EXPLANATION
1
The variable is assigned a regular expression containing an alphanumeric word
character
\w
, followed by a space
\s
, followed by another alphanumeric word char-
acter, followed by a nonalphanumeric word character
\W
. The metasymbol
\w
rep-
resents the character class
[A-Za-z0-9_].
The metasymbol
\W
represents the char-
acter class
[^A-Za-z0-9_],
and the metasymbol
\s
represents a whitespace
character (tab, space, newline, carriage return, formfeed).
2
The variable
textString
is assigned user input; in this example,
ABC D%
was en-
tered first.
3
The regular expression
test()
method will return
true
because the string
ABC D%
matches an alphanumeric character (
C
), followed by a space, another alphanu-
meric character (
D
) and a nonalphanumeric character (
%
) (see Figure 17.18). An
example of output where the pattern failed is shown in Figure 17.19.
Figure 17.18
The user entered
ABC D%
. It contained a word character, followed by
a whitespace, another word character, and a nonwhitespace.