1

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

3 Answers 3

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

alert(stringA.supplant(obj));

Demo - http://jsfiddle.net/saZGg/

Sign up to request clarification or add additional context in comments.

1 Comment

any way to map deep objects with dot notation?
2
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 "compiled" string.

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

1 Comment

.exec will return the string itself as its first argument, so you'll end up with the unaltered string prepended.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.