简体   繁体   English

在Actionscript中的StringUtil.substitue中使用变量名

[英]Use variable name in StringUtil.substitue in Actionscript

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. 如何在代码中使用变量名而不是使用{0}和{1}。

Please advice. 请指教。 Thanks. 谢谢。

Edit: 编辑:

The above code is quoted from http://www.rialvalue.com/blog/2010/05/10/string-templating-in-flex/ . 上面的代码引用自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 (ie using tokens like ${var1})". 它说:“还请注意,我们使用顺序来替换参数,相反,使用命名参数替换(即使用诸如$ {var1}之类的令牌)将相当容易”。 Therefore, I think it may be very easy to do that, but I don't know how to do. 因此,我认为这样做可能很容易,但是我不知道该怎么做。

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. 我认为,我用于占位符的格式是$ {placeholdername},因为它更安全。 But if you want to remove the dollar sign, change the regexp accordingly. 但是,如果要删除美元符号,请相应地更改正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM