HTML and CSS Reference
In-Depth Information
EXAMPLE
17.33 (
CONTINUED
)
</h3>
</body>
</html>
EXPLANATION
1
The string called
textString
is created.
2
The regular expression contains two subpatterns,
William
and
Rogers
, both en-
closed in parentheses.
3
When either the
String
object's
match()
method or the
RegExp
object's
exec()
method are applied to the regular expression containing subpatterns, an array is
returned, where the first element of the array is the regular expression string, and
the next elements are the values of the subpatterns.
4
The array elements are displayed, separated by commas.
5
The subpatterns are class properties of the
RegExp
object.
$1
represents the first
captured subpattern,
William
, and
$2
represents the second captured subpattern,
Rogers
. See Figure 17.35.
Figure 17.35
Capturing portions of a regular expression using the
RegExp
object.
EXAMPLE
17.34
<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(/(Tommy) (Savage)/, "$2, $1");
3
document.write(
newString
+"<br />");
</script>
</big>
</body>
</html>