首页 > 解决方案 > 用数组替换字符串中的相同字符,但在每次出现时使用下一个条目

问题描述

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

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"

标签: javascriptarraysstringcharacter

解决方案


您可以将 替换为?带有数组项的函数。

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);


推荐阅读