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?
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/
var arr = /(.*){{(\w)}}(.*)/.exec(stringA);
arr[2] = obj[arr[2]];
arr.shift(); // remove full string at start
var newString = arr.join("");
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.