Computer >> Computer tutorials >  >> Programming >> Javascript

Dynamically replace data based on matched RegEx - JavaScript?


For this, use replace() in JavaScript. The code is as follows −

Example

Following is the code −

var temp = `My name is {{fullName}} I live in {{countryName}}`;
var details = {
   "fullName": "David Miller",
   "countryName": "AUS"
}
replaceName = temp.replace(
   /\{\{(.+?)\}\}/g,
   (matching, value) => details[value.trim()]
);
console.log(replaceName);

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

node fileName.js.

Here, my file name is demo256.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo256.js
My name is David Miller I live in AUS