Replacing matched substrings
You can use the
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
(
) flag is set in the regular expression, and multiple matches are replaced because
ignoreCase
the
(
) flag is set. For more information, see
g
global
Expressions," on page
You can include the following
replacement text shown in the following table is inserted in place of the
$ Code
$$
$&
$`
$'
$n
nn
$
For example, the following shows the use of the
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
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));
218
Working with Strings
method to search for a specified pattern in a string and replace
285.
replacement codes in the replacement string. The
$
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 (
straight single quotation mark (
(
).
'
The portion of the string that follows the matched substring. This code
uses the straight single quotation mark (
The nth captured parenthetical group match, where n is a single digit, 1-
9, and $n is not followed by a decimal digit.
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.
Chapter 10, "Using Regular
) or the left curly single quotation mark
'
).
'
and
replacement codes, which
$2
$1
replace()
i
replacement code:
$
), not the
`
method. The matching