用数组替换字符以获得所需的结果,但每次出现时都使用下一个数组条目。 您对如何获得这个有什么想法吗?
var str = 'a ? c ? e ?';
var arr = ['b', 'd', 'f'];
var result_str = 'a b c d e f'; //desired outcome
//I was thinking about something like
result_str = 'a ? c ? e ?'.split('?').join(['b', 'd', 'f']);
//of course it just joins the array before replaceing, so the result is
result_str = "a b,d,f c b,d,f e b,d,f"
最佳答案
您可以将 ?
替换为获取数组项目的函数。
var string = 'a ? c ? e ?',
array = ['b', 'd', 'f'],
result = string.replace(/\?/g, (i => _ => array[i++])(0));
console.log(result);
以shift作为回调
var string = 'a ? c ? e ?',
array = ['b', 'd', 'f'],
fn = Array.prototype.shift.bind(array),
result = string.replace(/\?/g, fn);
console.log(result);
关于javascript - 将字符串中的相同字符替换为数组,但每次出现时都使用下一个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57269348/