繁体   English   中英

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

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

如果我有以下代码:

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

如何在代码中使用变量名而不是使用{0}和{1}。

请指教。 谢谢。

编辑:

上面的代码引用自http://www.rialvalue.com/blog/2010/05/10/string-templating-in-flex/
它说:“还请注意,我们使用顺序来替换参数,相反,使用命名参数替换(即使用诸如$ {var1}之类的令牌)将相当容易”。 因此,我认为这样做可能很容易,但是我不知道该怎么做。

看起来不可能。 从某种意义上说,它只允许从零开始的整数,因为您传递的是数量不确定的参数(参数在参数列表中的相对位置除外)。

这是一段代码,它将用名称替换令牌:

    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;
    }

采用:

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));

我认为,我用于占位符的格式是$ {placeholdername},因为它更安全。 但是,如果要删除美元符号,请相应地更改正则表达式。

暂无
暂无

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

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