如何制作过滤器和单词替换方法-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