0

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.

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.