Harsh Nagalla :
I am trying to replace keys from a url with multiple keys and parameters
Url Example
localhost/{id1}/xyz/{id2}?parameter={parameter}
My Current Implementation:
export const formatString = (url: string, args: any) => {
let str = url;
for (let key in args) {
str = str.replace(new RegExp('\\{' + key + '\\}', 'gi'), args[key]);
}
return str;
};
This implementation only works for single key.
Expected Result
localhost/DYM123/xyz/AXE123?parameter=ABCD
Is there a solution to replace all the keys and parameters at one go?
Hao Wu :
Try this?
const url = 'localhost/{id1}/xyz/{id2}?parameter={parameter}';
const args = {id1: 1, id2: 2, parameter: 'foo'};
const formatString = (url, args) => {
return url.replace(/\{(\w+)\}/ig, (_, key) => args[key]);
};
console.log(formatString(url, args));
In TypeScript:
export const formatString = (url: string, args: any) => {
return url.replace(/\{(\w+)\}/ig, (_, key) => args[key]);
};