如何用 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
广告