最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Javascript - The quickest and most efficient way to replace object-based values in text - Stack Overflow

programmeradmin2浏览0评论

I have an object that looks like this:

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

and I have a bunch of strings that look like this:

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

I want to replace {{(\w)}} with it's equivalent by going through obj and checking if it has my matched value for every string, but I'm sure there is a better and faster way to do so.

Any ideas?

I have an object that looks like this:

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

and I have a bunch of strings that look like this:

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

I want to replace {{(\w)}} with it's equivalent by going through obj and checking if it has my matched value for every string, but I'm sure there is a better and faster way to do so.

Any ideas?

Share Improve this question asked Oct 18, 2011 at 11:11 EliEli 2,7167 gold badges33 silver badges37 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Douglas Crockford wrote a function called supplant that does almost exactly what you want. I've altered the function slightly to match your double curly braces -

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./",
    stringB = "http://something.{{b}}./",
    stringC = "http://something./{{c}}";

alert(stringA.supplant(obj));

Demo - http://jsfiddle/saZGg/

var arr = /(.*){{(\w)}}(.*)/.exec(stringA);
arr[2] = obj[arr[2]];
arr.shift(); // remove full string at start
var newString = arr.join("");
  • Generally run a regular expression on the string,
  • execute and turn it into an array.
  • Swap one of the groups for the value in your object hash
  • join the array into your "piled" string.

Or use one of the .replace solutions which is arguebly more elegant.

This should do it:

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

It just looks up whether the object has a property with the captured name. If not, nothing is replaced.

Usage:

var str = format(stringA, obj);
发布评论

评论列表(0)

  1. 暂无评论