HTML and CSS Reference
In-Depth Information
EXAMPLE 17.42 ( CONTINUED )
<script type= "text/javascript">
1
var string="(408)-//[332]-1234@#!!!"
2
var newString= string.replace(/\W/g, "");
3
document.write("The original string: "+string);
document.write("<br>The new string: "+ newString +"<br>");
</script>
</big>
</body>
</html>
EXPLANATION
1
The string contains all kinds of characters, many of which are not letters or
numbers.
2
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, “”) ;
3
The new string is displayed after all nonalphanumeric characters are removed. See
Figure 17.44.
Figure 17.44 Any nonalphanumeric characters are removed.
17.5.5 Checking for Valid Social Security Numbers
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-
4444xyz .
 
 
Search WWH ::




Custom Search