HTML and CSS Reference
In-Depth Information
EXAMPLE
17.39 (
CONTINUED
)
document.write("<br>The new string: "+ newString +"<br>");
</script>
</big>
</body>
</html>
EXPLANATION
1
The string contains numbers, spaces, and dashes.
2
The variable called
regex
is assigned a regular expression, which means: Search for
one or more spaces or dashes, globally (multiple occurrences within the string).
3
The
replace()
method searches in the string for 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 re-
turned back to the original string:
var string=string.replace(regex, “”)
. See Figure
17.41.
Figure 17.41
The
replace()
method is used to remove any spaces or dashes.
Removing Unwanted Parentheses.
You might also want to remove parentheses
surrounding area codes or telephone numbers. This is a relatively simple regular expres-
sion used in the
replace()
method, as shown in the last example.
EXAMPLE
17.40
<html>
<head><title>Removing Parens</title></head>
<body bgcolor="magenta">
<big>
<font face="arial">
<h2>Removing Unwanted Parentheses, Spaces, and Dashes</h2>
<script type= "text/javascript">
1
var string="(408)-332-1234"
2
var regex = /[() -]+/g;
3
var newString=string.
replace(regex, "");