JavaScript如何将字符串中$n占位符动态替换为对应数组值
占位符批量替换实现方案
你可以通过正则全局匹配$n格式的占位符,结合字符串替换的回调方法实现通用的多占位符替换,无需提前限定占位符的数量:
const myStr = 'Hi $1, please check your $2 account status by clicking the link below'; const data = ['John', 'bank']; // 通用替换方法,支持任意数量$n格式占位符 function replaceTemplate(str, replaceList) { // 正则匹配所有$+数字的占位符 return str.replace(/\$(\d+)/g, (_, index) => replaceList[Number(index) - 1]) } const output = replaceTemplate(myStr, data) console.log(output) // 输出结果:Hi John, please check your bank account status by clicking the link below
方案特性:
- 自动适配$1、$2、$3...等任意数量的同格式占位符,只要数组长度和占位符数量一致即可正常运行
- 占位符序号和数组下标自动对齐:$1对应数组第一个元素,$2对应第二个,以此类推
- 后续需要新增占位符时,只需给数组对应位置补充元素即可,无需修改替换逻辑
内容的提问来源于stack exchange,提问作者nick
相关产品推荐
相关产品推荐

