Anže Jenšterle Anže Jenšterle -5 years ago 130
AngularJS Question

JS replace substring with keys in object

I am developing a general function inside a solution which would replace

where I pass the function the URL and item.

The item would be an object with keys

What would be the best way to find items with the structure
and replacing them with

Answer Source

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]);
    throw new Error('missing required property "' + key + '" in property collection');



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download