'replace url params with values of an object
I have a object like this:
let data = {
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?
Solution 1:[1]
Solution based on matching keys from params to the value of a regular expression from key url, followed by an update of that key.
On input: https://test.ir/apps/:type/:id/
On output: https://test.ir/apps/xyz/com.farsitel.bazaar/
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);
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Rob C |
