如何用 JavaScript 製作過濾器和單詞替換方法?


沒有內建函式來替換所有單詞出現的情況。你需要建立自己的函式。

假設我們的字串如下所示 −

var sentence = "Yes, My Name is John Smith. I live in US. Yes, My Favourite Subject is JavaScript";

示例

以下為程式碼 −

var sentence = "Yes, My Name is John Smith. I live in US. Yes, My Favourite Subject is JavaScript";
console.log(sentence);
function replaceYesWithHi(word, sentence, replaceValue) {
   return sentence.split(word).join(replaceValue);
}
var replacementofYesWithHi = replaceYesWithHi("Yes", sentence, "Hi");
console.log(replacementofYesWithHi);

要執行上述程式,請使用以下命令 −

node fileName.js.

在此處,我的檔名是 demo240.js。

輸出

輸出如下所示 −

PS C:\Users\Amit\javascript-code> node demo240.js
Yes, My Name is John Smith. I live in US. Yes, My Favourite Subject is JavaScript
Hi, My Name is John Smith. I live in US. Hi, My Favourite Subject is JavaScript

更新於: 03-Oct-2020

218 次閱讀

開啟你的 職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.