HTML and CSS Reference
In-Depth Information
EXPLANATION
1
A string is assigned to the variable, called string .
2
The replace() method will search for the pattern Tommy Savage . Because the
search side of the replace() method contains the pattern Tommy enclosed in paren-
theses and the pattern Savage enclosed in parentheses, each of these subpatterns
will be stored in $1 and $2 , respectively. A third pattern would be stored in $3 and
a fourth pattern in $4 , and so on. On the replacement side of the replace() method,
$2 and $1 are replaced in the string, so that Savage is first, then a comma, and then
Tommy . The first and last names have been reversed.
3
The new string is displayed. See Figure 17.36.
Figure 17.36 Output from Example 17.34.
EXAMPLE 17.35
<html>
<head><title>Capture and Replace</title></head>
<body>
<big>
<script type = "text/javascript">
1 var string="Tommy Savage:203-123-4444:12 Main St."
2 var newString=string.replace(/(\w+)\s(\w+)/, "$2, $1");
3 document.write(newString +"<br />");
</script>
</big>
</body>
</html>
EXPLANATION
1
A string is created to be used by the replace() method in line 2.
2
The replace() method searches for one or more alphanumeric word characters,
followed by a single space, and another set of alphanumeric word characters. The
word characters are enclosed in parentheses, and thus captured. $1 will contain
Tommy , and $2 will contain Savage . On the replacement side, $1 and $2 are re-
versed. After the replacement is made, a new string is created.
3
The value of newString shows that the capturing and the substitution occurred
successfully, leaving the remainder of the string as it was. See Figure 17.37.
Search WWH ::




Custom Search