You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:48:00