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 badges3 Answers
Reset to default 6Douglas 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);