将正则表达式匹配替换为值数组

时间:2018-12-26 04:38:19

标签: javascript

我有一个正则表达式来查找字符串中带有???的文本。

const paragraph = 'This ??? is ??? and ???. Have you seen the ????';
const regex = /(\?\?\?)/g;
const found = paragraph.match(regex);

console.log(found);

是否可以用数组中的值顺序替换每个匹配项?

例如使用['cat', 'cool', 'happy', 'dog']数组,我希望结果为'This cat is cool and happy. Have you seen the dog?'

我看到了String.prototype.replace(),但是它将替换所有值。

1 个答案:

答案 0 :(得分:2)

使用替换函数,该替换函数从替换字符串数组中shiftshift删除并返回第0个索引处的项):

const paragraph = 'This ??? is ??? and ???. Have you seen the ????';
const regex = /(\?\?\?)/g;
const replacements = ['cat', 'cool', 'happy', 'dog'];
const found = paragraph.replace(regex, () => replacements.shift());

console.log(found);

(如果数组中没有足够的项目来替换所有项目,则其余???会被undefined替换)

相关问题