遍历数组并编辑字符串JavaScript
假设我们必须编写一个函数,该函数translate()接受一个字符串作为第一个参数,然后接受任意数量的单词。
该字符串实际上将包含n$符号,如下所示-
This $0 is more $1 just a $2. Then there will be 3 strings which will replace the corresponding places.
例如-
如果函数调用是这样的-
translate(‘This $0 is more $1 just a $2.’, ‘game’, ‘than’, ‘game’);
该函数的输出应为-
This game is more than just a game.
此功能或多或少类似于JavaScript中的模板注入。
因此,让我们为该函数编写代码-
我们将在这里使用String.prototype.replace()方法。我们知道,如果我们使用正则表达式模式来匹配所有匹配项并使用一个函数作为第二个参数,则它将为每次匹配执行。我们将在这里做完全一样的事情。
这样做的代码将是-
示例
const str = 'This $0 is more $1 just a $2';
const translate = (str, ...texts) => {
const regex = /\$(\d+)/gi;
return str.replace(regex, (item, index) => {
return texts[index];
});
};
console.log(translate(str, 'game', 'just', 'game'));输出结果
控制台中的输出将为-
This game is more just just a game
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短