JavaScript中如何根据名字列表动态替换模板占位符生成对应结果
模板字符串批量遍历替换实现方法
前置已知条件
- 预定义名字列表:
let firstnameList = ["Jan", "Mark", "Doe"] - 图形化界面采集到的用户输入消息模板:
let message = "Hello {firstname}",其中*{firstname}为需要被动态替换的占位符*
核心实现逻辑
不需要引入额外第三方依赖,通过内置字符串替换方法匹配占位符,逐一遍历名字列表完成替换即可:
// 逐一遍历名字列表的每一项 firstnameList.forEach(currentName => { // 替换模板中{firstname}占位符为当前遍历到的名字 const renderedText = message.replace("{firstname}", currentName) // 按要求格式输出结果 console.log(`message = ${renderedText}`) })
如果需要兼容用户输入模板时的不规范写法(比如占位符前后多打了空格、大小写不统一),可以把精确字符串替换换成正则匹配,提升模板适配能力:
// 正则规则:匹配任意位置的{firstname},忽略括号内的前后空格、大小写差异 const renderedText = message.replace(/\{\s*firstname\s*\}/gi, currentName)
实际输出效果
运行上述代码后,控制台会按顺序输出符合要求的内容:
message = Hello Jan
message = Hello Mark
message = Hello Doe
内容的提问来源于stack exchange,提问作者Corioste
相关产品推荐
相关产品推荐

