Anže Jenšterle Anže Jenšterle - 4 months ago 18
AngularJS Question

JS replace substring with keys in object

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
?

Answer

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/

Comments