Reputation: 73
I am developing a general function inside a solution which would replace /endpoint/{item.id}/disable/{item.name}
with /endpoint/123/disable/lorem
where I pass the function the URL and item.
The item would be an object with keys id
and name
.
What would be the best way to find items with the structure {item.KEY}
and replacing them with item.KEY
?
Upvotes: 0
Views: 543
Reputation: 22635
If you don't want to use eval, maybe use something like this:
var item = {
id: 123,
KEY: "lorem"
};
function pick(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
and then
str.replace(/{.*?}/g, function(match){ // match {...}
var path = match.substring(1,match.length-1); // get rid of brackets.
return pick(scope, path); //get value and replace it in string.
});
Upvotes: 1
Reputation: 896
the best way to solve this is passing a function to handle a regex. I modified your parameters to make the mapping easier- I'm sure you can change this on your own if necessary
var url = '/endpoint/{id}/disable/{name}'; //I modified your parameters
var definition = { id: 123, name: 'lorem' };
url = url.replace(/{([^}]*)}/g, function (prop) {
var key = prop.substr(1, prop.length - 2);
if (definition[key])
return encodeURIComponent(definition[key]);
else
throw new Error('missing required property "' + key + '" in property collection');
});
//alert(url);
fiddle: https://jsfiddle.net/wovr4ct5/2/
Upvotes: 2