javascript - 用数组替换字符串中的相同字符,但在每次出现时使用下一个条目
问题描述
用数组替换字符以获得所需的结果,但在每次出现时使用下一个数组条目。你对如何得到这个有什么想法吗?
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);
推荐阅读
- android - 是否可以通过 Intent 找出哪个应用与我的应用共享了某些内容?
- javascript - JSON 用引号打断
- java - 如何在 Google Cloud 上使用 gecko 驱动程序运行 Java selenium
- html - 如何让我的图像显示在我的页面上?
- python - 如何在 python 中抓取某些 html 类
- android - 如何在 Android 中禁用文件共享
- html - 如何从 launch.js 检索旧代码
- java - 在给定的世界和 BlockPos 中放置一个块
- c - x64 参数和返回值调用约定
- javascript - 如何使用 Chrome 的 React Developer Tools 扩展设置日期?