迴圈遍歷陣列並編輯字串 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

更新於: 24-8-2020

676 次瀏覽

啟動你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.