javascript - 将字符串中的相同字符替换为数组,但每次出现时都使用下一个条目

标签 javascript arrays string character

用数组替换字符以获得所需的结果,但每次出现时都使用下一个数组条目。 您对如何获得这个有什么想法吗?

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/

相关文章:

javascript - react 错误 : react/jsx-no-undef by react-bootstrap

javascript - 如何在 ExtJS 中滚动到表单末尾

javascript - knockout : More confusion with indexOf returning -1

java - 原始数组初始化没有值?

java - 需要按 'R' 、 'B' 、 'W' 的顺序对任意长度的字符数组进行排序

javascript - 将数组转换为字符串并获取子字符串

javascript - Umbraco 属性编辑器不工作

c++ - bool 数组获取意外的默认值

arrays - 将动态分配的字符串数组从 C 传递到 Fortran

c++ - C 字符串的奇怪结果