首页 > 解决方案 > 从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('')

有更好的解决方案吗?

我正在考虑获取索引,这样我就可以替换找到的每个索引,但替换没有从它回调中获取索引的犯规

标签: javascriptstringreplace

解决方案


___您可以使用该标志进行全局匹配,并通过播种起始值 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);


推荐阅读