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

Eli*_*Eli 1 javascript regex replace

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

var obj = {
    a: "text",
    b: "text 2",
    c: "text 3",
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

var stringA = "http://{{a}}.something.com/",
    stringB = "http://something.{{b}}.com/",
    stringC = "http://something.com/{{c}}";
Run Code Online (Sandbox Code Playgroud)

我希望{{(\w)}}通过obj检查它是否等同于检查它是否具有每个字符串的匹配值,但我确信有更好更快的方法.

有任何想法吗?

ipr*_*101 6

道格拉斯·克罗克福德(Douglas 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));
Run Code Online (Sandbox Code Playgroud)

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