Was it helpful?

Question

How to make filter and word replacement method - JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

There is no in-built function to replace all occurrences of word. You need to create your own function.

Let’s say the following is our string −

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

Example

Following is the code −

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);

To run the above program, use the following command −

node fileName.js.

Here, my file name is demo240.js.

Output

The output is as follows −

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
raja
Published on 03-Oct-2020 18:54:22
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top