views:

50

answers:

1

If I have the following code:

var value : String = StringUtil.substitute("The value {0} requested is {1}", user, value);

How can I use the variable name instead of using {0} and {1} in the code.

Please advice. Thanks.

Edit:

The above code is quoted from http://www.rialvalue.com/blog/2010/05/10/string-templating-in-flex/.
It says that "Also note that we’re substituting the parameters using the order, it’d would fairly easy to do a named-parameter subsitution instead (i.e. using tokens like ${var1})". Therefore, I think it may be very easy to do that, but I don't know how to do.

+2  A: 

Looks like it's not possible. And kind of makes sense that it allows zero based ints only, since you're passing a variable number of parameters that you're not identifying (except for their relative position in the params list).

Here's a piece of code that will replace tokens by name:

    public static function replacePlaceholders(input:String,replacementMap:Object):String {
        // '${', followed by any char except '}', ended by '}'
        return input.replace(/\${([^}]*)}/g,function():String {
            return replaceEntities(arguments,replacementMap);
        });

    }

    private static function replaceEntities(regExpArgs:Array,map:Object):String {
        var entity:String       = String(regExpArgs[0]);
        var entityBody:String   = String(regExpArgs[1]);
        return (map[entityBody]) ? map[entityBody] : entity;
    }

Use:

var test:String = "Hello there ${name}, how is the ${noun} today?";
var replacementMap:Object   = { 
    name    :   "YOUR_NAME_HERE",
    noun    :   "YOUR_NOUN_HERE"
};

trace(StringUtils.replacePlaceholders(test,replacementMap));

The format I'm using for the placeholders is ${placeholdername}, since it's safer, I think. But if you want to remove the dollar sign, change the regexp accordingly.

Juan Pablo Califano
Would this be an extension of the StringUtil class ? shown by StringUtils ?
phwd
Not really, it's part of a utility class I wrote.
Juan Pablo Califano