How to detect and replace all the array elements in a string using RegExp in JavaScript? 



Let’s say we have the following string −

var sentence= "My Name is John Smith. I live in UK. My Favourite Subject is JavaScript."

We need to replace the following words in the above sentence with a specific value “Not Available” −

var values = ['John','Smith','UK','JavaScript']

So, the output should be −

My Name is Not Available Not Available. I live in Not Available. My Favourite Subject is Not Available.

You can use regular expression to implement what we discussed above.

Example

Following is the code −

var values = ['John','Smith','UK','JavaScript']
var sentence= "My Name is John Smith. I live in UK. My Favourite Subject is JavaScript."
var regularExpression = new RegExp (values.join('|'), 'gim')
sentence = sentence.replace(regularExpression, 'Not Available');
console.log(sentence);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo279.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo279.js
My Name is Not Available Not Available. I live in Not Available. My Favourite Subject is Not Available.

Advertisements