我有一个字符串,但在字符串中的某些点它具有动态值。 我想找到字符串中的这些点并将它们替换为数组中的值。
假设我有:
var array = ['string', 'value'];
var string = 'This is a {1}, and this is a {2}.';
现在我需要找到一种方法,将 {1} 替换为数组中第一个索引的值,并将 {2} 替换为数组中第二个索引的值。
所以字符串会像这样:
This is a string, and this is a value.
这看起来很简单,但我对此感到很困惑。我找不到轻松做到这一点的方法。
最佳答案
您可以使用 replace
使用正则表达式和函数:
string.replace(/{(\d+)}/g, function(match, n) {
return array[n-1];
});
您还可以查看n < 1 || n > array.length
在数字超出范围时提供后备值。
或者,新的 ES6 方式是使用 tagged template strings
function tag(strings, ...values) {
var parts = [];
for(var i=0; i<strings.length; ++i)
parts.push(strings[i], array[values[i]-1]);
return parts.join('');
}
tag`This is a ${1}, and this is a ${2}.`
关于Javascript - 查找并用数组中的值替换字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35528583/