HTML and CSS Reference
EXAMPLE 17.40 ( CONTINUED )
document.write("The original string: "+string);
document.write("<br>The new string: "+ newString +"<br>");
The string contains numbers, parentheses, spaces, and dashes.
The variable called regex is assigned a regular expression, which means: Search for
one or more parentheses (open or closed), spaces or dashes, globally (multiple oc-
currences within the string).
The replace() method searches in the string for parentheses, spaces, and dashes,
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,
“”) . See Figure 17.42.
Figure 17.42 Parentheses, as well as spaces and dashes, are removed. Numbers or letters
Removing any Nondigits. A character that is not a digit can be represented as [^0-
9] or as \D in a regular expression. You might want to remove any characters that are not
digits in the user's input such as zip codes or phone numbers. This can also be done sim-
ply with a regular expression and the replace() method, as shown in Example 17.41.
<head><title>Removing all Nondigits</title></head>