繁体   English   中英

Javascript-替换文本中基于对象的值的最快,最有效的方法

[英]Javascript - The quickest and most efficient way to replace object-based values in text

我有一个看起来像这样的对象:

var obj = {
    a: "text",
    b: "text 2",
    c: "text 3",
    ...
}

我有一堆看起来像这样的字符串:

var stringA = "http://{{a}}.something.com/",
    stringB = "http://something.{{b}}.com/",
    stringC = "http://something.com/{{c}}";

我想通过遍历obj并检查它是否具有每个字符串的匹配值来替换{{(\\w)}}以使其等效,但是我敢肯定有一种更好,更快的方法。

有任何想法吗?

道格拉斯Crockford的写了一个函数调用supplant ,做几乎正是你想要的。 我对功能做了些微修改,以匹配您的双花括号-

if (typeof String.prototype.supplant !== 'function') {
    String.prototype.supplant = function (o) {
        return this.replace(/{{([^{}]*)}}/g, function (a, b) {
            var r = o[b];
            return typeof r === 'string' ? r : a;
        });
    };
}

var obj = {
    a: "text",
    b: "text 2",
    c: "text 3"
}

var stringA = "http://{{a}}.something.com/",
    stringB = "http://something.{{b}}.com/",
    stringC = "http://something.com/{{c}}";

alert(stringA.supplant(obj));

演示-http://jsfiddle.net/saZGg/

var arr = /(.*){{(\w)}}(.*)/.exec(stringA);
arr[2] = obj[arr[2]];
arr.shift(); // remove full string at start
var newString = arr.join("");
  • 通常在字符串上运行一个正则表达式,
  • 执行并将其转换为数组。
  • 交换一组对象中的对象哈希值
  • 将数组连接到“已编译”字符串中。

或者使用.replace解决方案之一,该解决方案显然更优雅。

应该这样做:

function format(str, values) {
    return str.replace(/{{(\w)}}/g, function(match, name) {
        return values[name] || match;
    });
}

它只是查询对象是否具有带有捕获名称的属性。 如果没有,则什么也不会取代。

用法:

var str = format(stringA, obj);

暂无
暂无

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

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