How to replace value of keys and parameters from a url?

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]);
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=26238&siteId=1