Building Blocks you should not target low coupling, instead target appropriate coupling – Mike Labriola (@mlabriola)

15Jan/081

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
}
  • 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