javascript - 从javascript中的字符串数组替换字符串上的某些字符
问题描述
我有一个这样的字符串
const text = 'hello ___ where ___ test ___'
还有这样的数组
const blankData = ['there', 'you', 'it']
我的预期结果是
hello there where you test it
我试过的
const result = text?.replaceAll('___', (index, x) => {
return blankData[index]
})
我也有这样不优雅的想法
const mapped = text
.split('___')
.map((textitself, index) => textitself + blankData?.[index])
mapped.pop()
const result = mapped.join('')
有更好的解决方案吗?
我正在考虑获取索引,这样我就可以替换找到的每个索引,但替换没有从它回调中获取索引的犯规
解决方案
___
您可以使用该标志进行全局匹配,并通过播种起始值 0 并在每次迭代中递增它来/g
获取替换索引。blankData
const text = 'hello ___ where ___ test ___';
const blankData = ['there', 'you', 'it'];
result = text.replace(/___/g, (i => _ => blankData[i++])(0));
console.log(result);
请注意,如果您不想有多个匹配项,_________
但也不想匹配单个匹配项_
,则可以将_{3,}
其用作匹配下划线 3 次或更多次的模式。
const text = 'h_ello ______ where ___ test ___';
const blankData = ['there', 'you', 'it'];
result = text.replace(/_{3,}/g, (i => _ => blankData[i++])(0));
console.log(result);
推荐阅读
- python - Python Discord 机器人故障排除
- python - pandas DataFrame中条件成对行操作的最有效方法
- xamarin - 为什么 SkiaSharp Touch SKTouchAction.Moved 事件不起作用?
- acumatica - 如何将图像嵌入 Acumatica 报告超链接?
- c# - Unity 3d 如何让场景实例接收面向对象的脚本
- c# - 调用 Hangfire BackgroundJob.Enqueue 方法时是否应该使用异步包装器?
- android - 由于访问令牌失败,如何重试现有的失败请求
- python - K-means、词袋、Word嵌入文本分类CSV文件和检索数据关联
- dji-sdk - 仅在没有 GPS 的情况下控制 M100
- python - 多项式次数越高,多元线性回归不会变得更准确?