我想替换出现的“?”与数组中的值
示例:
var s = "hello ? , my name is ?";
我想使用类似的东西
var result= s.replace('?',['john','david']); /** does not work **/
console.log(result) /** "hello john, my name is david" **/
最佳答案
可以通过使用.replace
来实现这一点带有正则表达式和函数。您还需要一个外部变量来递增。我称之为i
。
var s = "hello ? , my name is ?";
var i = 0;
var result = s.replace(/\?/g, function() {
return ['john','david'][i++];
});
console.log(result);
关于Javascript - 用数组替换字符串值中的相同匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61058478/