【问题标题】:Use variable name in StringUtil.substitue in Actionscript在 Actionscript 的 StringUtil.substitue 中使用变量名
【发布时间】:2010-06-03 16:07:00
【问题描述】:

如果我有以下代码:

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} 之类的标记)相当容易”。因此,我认为这样做可能很容易,但我不知道该怎么做。

【问题讨论】:

    标签: apache-flex flash actionscript-3


    【解决方案1】:

    看起来不可能。并且它只允许基于零的整数是有道理的,因为您传递的参数数量不定,但您没有识别(除了它们在参数列表中的相对位置)。

    这里有一段代码将用名称替换标记:

        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},因为我认为它更安全。但是,如果您想删除美元符号,请相应地更改正则表达式。

    【讨论】:

    • 这会是 StringUtil 类的扩展吗?由 StringUtils 显示?
    • 不是真的,它是我编写的实用程序类的一部分。
    猜你喜欢
    • 1970-01-01
    • 2013-04-27
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多