Home > Software engineering >  replace url params with values of an object
replace url params with values of an object

Time:04-18

I have a object like this:

{
   url: "https://test.ir/apps/:type/:id/",
   params: {
      id: "com.farsitel.bazaar",
      type: "xyz",
   },
   query: {
      ref: "direct",
      l: "en",
   },
}

I want to replace :type and :id in url with equivalent key to each from params object. what is the best solution in javascript?

CodePudding user response:

Could you just use String.replace?

const data = {
   url: "https://test.ir/apps/:type/:id/",
   params: {
      id: "com.farsitel.bazaar",
      type: "xyz",
   },
   query: {
      ref: "direct",
      l: "en",
   },
}

const url = data.url.replace(":type", data.params.type).replace(":id", data.params.id);

console.log(url)

CodePudding user response:

Solution based on a regular expression and updating key url in the object.

let data = {
    url: "https://test.ir/apps/:type/:id/",
    params: {
        id: "com.farsitel.bazaar",
        type: "xyz",
    },
    query: {
        ref: "direct",
        l: "en",
    },
};

let new_url = data.url.replace(/:(\w )/g, (match, key) => data.params[key] || match);

data.url = new_url;

console.log(data);

  • Related