- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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