HTML and CSS Reference
EXAMPLE 17.42 ( CONTINUED )
var newString= string.replace(/\W/g, "");
document.write("The original string: "+string);
document.write("<br>The new string: "+ newString +"<br>");
The string contains all kinds of characters, many of which are not letters or
The regular expression, /\W/g , means: Search globally for any nonalphanumeric
characters ( \W ). The replace() method searches for nonalphanumeric characters
and replaces them with the empty string, “” , returning the resulting string to new-
String . To change the original string, the return value of the replace() method can
be returned back to the original string: var string=string.replace(regex, “”) ;
The new string is displayed after all nonalphanumeric characters are removed. See
Figure 17.44 Any nonalphanumeric characters are removed.
A Social Security number contains exactly nine numbers. There might be dashes to sep-
arate the first three numbers and the last four numbers. The dashes should be optional.
Example 17.43 demonstrates a regular expression that tests for three digits, followed by
an optional dash, followed by two more digits, an optional dash, and finally four digits.
The beginning and end of line anchors ensure that the user does not enter extraneous
characters on either end of his or her Social Security number, such as abd444-44-