Javascript 正则替换两个符号之间的字符

实现场景:给地址的参数动态赋值

const path = "?aa={aaa}&bb={bbb}"
const variablePara = {aaa: 1}
const keys = path.match(/\{([\s\S]*?)\}/g);  
console.log(keys) // ["{aaa}", "{bbb}"]
let nextPath = path;
keys?.forEach((key) => {
  nextPath = nextPath.replace(
    key,
    variablePara[key.replace(/\{/g, '').replace(/\}/g, '')] || '',
  );
});
console.log(nextPath) // ?aa=1&bb=

你可能感兴趣的:(Javascript 正则替换两个符号之间的字符)