Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 731
Harsh Nagalla Avatar asked Nov 25 '25 21:11

Harsh Nagalla


1 Answers

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]);
};
like image 106
Hao Wu Avatar answered Nov 28 '25 12:11

Hao Wu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!