I am trying to replace values in a string with the comparable jSON property in an object.
var value = "/sessions/:sessionId/events/:id";
var result = replace(value, { sessionId : 1 , id : 23 });
// result : "/sessions/1/events/23"
console.log(result);
Is it possible with JavaScript (I'm sure it is)? Not sure about the most efficient way to do this and how to handle it when all the values inside the template string are not matched.
Thanks in advance.
Update (Solution)
var url = function (template, parameters) {
var extra = [];
for (param in parameters) {
if (value.indexOf(param) < 0) {
extra.push(param + '=' + parameters[param]);
}
}
var result = template.replace(/:(\w+)/g, function (substring, match) {
var routeValue = parameters[match];
if (!routeValue) {
throw "missing route value for " + match + ' in "' + template +'"';
}
return routeValue;
});
if (result.indexOf("/:") > 0) {
throw "not all route values were matched";
}
return (extra.length === 0) ? result : result + "?" + extra.join("&");
};
var value = "/sessions/:sessionId/events/:id";
var data = {
sessionId: 1,
id: 23,
term: "butter"
};
// result : /sessions/1/events/21?term=butter
console.log(url(value, data));
{ sessionId : 1 , id : 23 }is an object literal,'{"sessionId": 1, "id": 23}'(a string) is JSON.$resourceurl template, looking at github.com/angular/angular.js/blob/master/src/ngResource/…setUrlParams()does the magic and also handles url encoding.