首页 > 解决方案 > 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 出现的数量一样长。

标签: javascript

解决方案


如果数组长度和出现次数($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)

推荐阅读