循环遍历数组并编辑字符串 JavaScript

javascriptweb developmentobject oriented programming更新于 2025/10/2 20:28:17

假设,我们必须编写一个函数,即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’);

该函数的输出应为 −

这个游戏不仅仅是一个游戏。

此功能或多或少类似于 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

相关文章


有用资源