ADOBE FLEX 3
Developer Guide
138
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));
function usdToEuro(matchedSubstring:String, capturedMatch1:String, index:int,
str:String):String
{
var usd:String = capturedMatch1;
usd = usd.replace(",", "");
var exchangeRate:Number = 0.853690;
var euro:Number = usd * exchangeRate;
const euroSymbol:String = String.fromCharCode(8364);
return euro.toFixed(2) + " " + euroSymbol;
}
When you use a function as the second parameter of the replace() method, the following arguments are passed to
the function:
The matching portion of the string.
Any capturing parenthetical group matches. The number of arguments passed this way will vary depending on
the number of parenthetical matches. You can determine the number of parenthetical matches by checking
arguments.length - 3 within the function code.
The index position in the string where the match begins.
The complete string.
Converting strings between uppercase and lowercase
As the following example shows, the toLowerCase() method and the toUpperCase() method convert alphabetical
characters in the string to lowercase and uppercase, respectively:
var str:String = "Dr. Bob Roberts, #9."
trace(str.toLowerCase()); // dr. bob roberts, #9.
trace(str.toUpperCase()); // DR. BOB ROBERTS, #9.
After these methods are executed, the source string remains unchanged. To transform the source string, use the
following code:
str = str.toUpperCase();
$
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.
$ Code Replacement Text

Get ADOBE® FLEX® 3: PROGRAMMING ACTIONSCRIPT™ 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.