遍历数组并编辑字符串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
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬