javascript - Javascript 用数组值替换字符串 $n
问题描述
所以我有这个字符串:
const myStr = 'Hi $1, please check your $2 account status by clicking the link below';
const data = ['John', 'bank'];
我想用 John 替换 $1,用银行替换 $2。但我希望它灵活一些,这样我就可以有更多的参数,比如 $3、$4 等等。该数组将始终与 $n 出现的数量一样长。
解决方案
如果数组长度和出现次数($1、$2 等)在每种情况下都相同,那么您可以执行以下操作:
const myStr = 'Hi $1, please check your $2 account status by clicking the link below';
const data = ['John', 'bank'];
function interpolate(string, arr) {
arr.forEach((item, index) => (string = string.replace(`$${index + 1}`, item)))
return string
}
// Call it to see the result
const result = interpolate(myStr, data);
console.log(result)
推荐阅读
- wordpress - Wordpress 分页有时无法加载/显示
- linux - Linux Socket 超时适用于 WSL,但不适用于 Ubuntu
- python - 使用python分割拼贴图像
- javascript - 如何从函数返回的对象键和值生成一种类型的字符串文字?
- hibernate - 如何在 JPA 中初始化几层 LAZY 实体?
- python - 从网站获取 JSON 数据的不同方法
- vue.js - 登录后 VUA 和 AUTH0 未登陆上一个 URL
- node.js - 如何将 fluent-ffmpeg 屏幕截图的输出作为缓冲区而不是直接写入磁盘?
- android - 访问路径...被拒绝 - Xamarin Android
- python - 在类的实例中查找 max()