HTML and CSS Reference
EXAMPLE 17.41 ( CONTINUED )
<h3>If it's not a number, remove it!</h3>
var string="phone is (408)-//-1234@#!!!"
var newString= string.replace(/\D/g, "");
document.write("The orginal string: "+string);
document.write("<br>The new string: "+ newString +"<br>");
The string contains all kinds of characters, many of which are not numbers.
The replace() method searches in the string for all nondigit characters, /\D/g , and if
it finds any, replaces them with the empty string, “” , returning the resulting string
to newString . 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 the nondigit characters were replaced with
nothing (i.e., they were removed). See Figure 17.43.
Figure 17.43 Only numbers will remain in the string. All other characters are
Removing any Nonalphanumeric Characters. A nonalphanumeric word char-
acter [^0-9a-zA-Z_] , any character that is not a letter, number, or the underscore, can be
represented as \W . Again we can use the replace() method to remove those characters
from a string.
<head><title>Removing Nonalphanumeric Characters</title></head>
<h3>If it's not a number or a letter, remove it!</h3>