How to make filter and word replacement method - JavaScript?
https://www.tutorialspoint.com/how-to-make-filter-and-word-replacement-method-javascript
Question
How to make filter and word replacement method - JavaScript?
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
Advertisements
Not affiliated with Tutorialspoint