我是 JavaScript 新手。如果数组键值与字符串值匹配,我想替换数组中的字符串值
这是我的以下代码:
var arr= [];
arr[11] = 'XYZ';
arr[12] = 'ABC';
var string = "11-12";
我的输出将是:
var str ="XYZ-ABC";
最佳答案
使用String#replace
带有回调的方法。
var arr = [];
arr[11] = 'XYZ';
arr[12] = 'ABC';
var string = "11 - 12";
// match all digits in string and replace it with
// corresponding value in `arr`
var res = string.replace(/\d+/g, function(m) {
return arr[m];
})
console.log(res);
关于Javascript搜索替换数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38952052/