Reputation: 10839
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.
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));
Upvotes: 2
Views: 3217
Reputation: 227240
A regex would work just fine here.
var value = "/sessions/:sessionId/events/:id";
var obj = { sessionId : 1 , id : 23 };
var result = value.replace(/:(\w+)(\/|\b)/g, function(substring, match, nextMatch){
return obj[match] + nextMatch;
});
Upvotes: 6
Reputation: 48415
Assuming you have the following javascript object:
var myObject = { sessionId : 1 , id : 23 };
you can loop each property and do a replace on the original string...
var value = "/sessions/:sessionId/events/:id";
for(var item in myObject){
value = value.replace(item, myObject[item]);
}
//value = "/sessions/:1/events/:23"
It is not clear if you want to keep the :
characters or not. If not, then you can just include that in your replace function:
value = value.replace(':' + item, myObject[item]);
Checking for missing parameters
If you have any extra values in your object that do not exist in your input string, then they will not have any effect. If however, you want to take action if one of the items is not found in the original string, then you can do a check in the loop:
var noMatch = false;
for(var item in myObject){
if(value.indexOf(item) < 0){
noMatch = true;
}
value = value.replace(item, myObject[item]);
}
if(noMatch){
//something is wrong!
}
Dealing with JSON
If you do actually have a JSON string to begin with, you can convert that to an object with the following:
var jsonString = '{"sessionId": 1, "id": 23}';
var myObject = JSON.parse(jsonString);
Upvotes: 3
Reputation: 3727
here is another way of doing it.
http://jsfiddle.net/rayweb_on/suHej/
var value = "/sessions/:sessionId/events/:id";
var source = { sessionId : 1 , id : 23 };
var result = value.replace(":sessionId",source.sessionId);
var result = result.replace(":id",source.id);
console.log(result);
Upvotes: 1