HTML and CSS Reference
In-Depth Information
EXAMPLE
17.41 (
CONTINUED
)
<h3>If it's not a number, remove it!</h3>
<script type = "text/javascript">
1
var string="phone is (408)-//[332]-1234@#!!!"
2
var newString=
string.replace(/\D/g, "");
document.write("The orginal string: "+string);
3
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 numbers.
2
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, “”)
;
3
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
removed.
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.
EXAMPLE
17.42
<html>
<head><title>Removing Nonalphanumeric Characters</title></head>
<body bgcolor="magenta">
<big>
<h3>If it's not a number or a letter, remove it!</h3>