遍历数组并编辑字符串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 官宣新年祝福语简短