Actionscript string replacement and international currency.

This made me a little nostalgic for the olden days when a vacation to Europe was a remote possibility:

?View Code ACTIONSCRIPT
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;
}

Related posts:

  1. Enumerating data types in Actionscript 3 (AS3)
  2. Christian Cantrell’s ever-growing selection of useful Actionscript 3/AIR libraries.
  3. FlexUnit – Some useful examples and tutorials covering unit testing in Flex and Actionscript 3.0
  4. KitchenSync – open-source Actionscript 3 tweening and timing animation library

  • I rather use the following regular expression

    /\$([\d,]+)\.(\d+)/

    The one you have above is

    /\$([\d,]+.\d+)+/i;

    the difference is that you are matching a dot between
    numbers, but in regular expressions a dot basically means
    any char meaning you could match anything instead of the dot
    for example.

    "$324!234"
    "$324x234"
    "$324%234"

    and plus the first one independently captures both the first and second number after a dot, making sure that it is a dot. you might wanna make a stronger regex though because in both cases you could match something like

    first case
    "$,,,,,,,"
    "$,,0,0,,"

    second case
    "$,,,,,,,"
    "$3,4%2,4"

    I would recomend to remove all commas before getting the price
    or make a more specific regex for the problem presented above

    cheers!
blog comments powered by Disqus

every-sword
every-sword