User Guide

218 Working with Strings
Replacing matched substrings
You can use the replace() method to search for a specified pattern in a string and replace
matches with the specified replacement string, as the following example shows:
var str:String = "She sells seashells by the seashore.";
var pattern:RegExp = /sh/gi;
trace(str.replace(pattern, "sch"));
//sche sells seaschells by the seaschore.
Note that in this example, the matched strings are not case-sensitive because the i
(
ignoreCase) flag is set in the regular expression, and multiple matches are replaced because
the
g (global) flag is set. For more information, see Chapter 10, “Using Regular
Expressions,” on page 285.
You can include the following
$ replacement codes in the replacement string. The
replacement text shown in the following table is inserted in place of the
$ replacement code:
For example, the following shows the use of the
$2 and $1 replacement codes, which
represent the first and second capturing group matched:
var str:String = "flip-flop";
var pattern:RegExp = /(\w+)-(\w+)/g;
trace(str.replace(pattern, "$2-$1")); // flop-flip
You can also use a function as the second parameter of the replace() method. The matching
text is replaced by the returned value of the function.
var str:String = "Now only $9.95!";
var price:RegExp = /\$([\d,]+.\d+)+/i;
trace(str.replace(price, usdToEuro));
$ Code Replacement Text
$$
$
$&
The matched substring.
$`
The portion of the string that precedes the matched substring. This
code uses the straight left single quotation mark character (
`), not the
straight single quotation mark (
') or the left curly single quotation mark
(
).
$'
The portion of the string that follows the matched substring. This code
uses the straight single quotation mark (
).
$n The nth captured parenthetical group match, where n is a single digit, 1-
9, and $n is not followed by a decimal digit.
$nn The nnth captured parenthetical group match, where nn is a two-digit
decimal number, 01–99. If the nnth capture is undefined, the
replacement text is an empty string.