String.replace not working in node.js express server

I need to read a file and replace some texts in this file with dynamic content. When I tried string.replace, it does not work for the data that I read from the file. But for the string, it works. I am using node.js and express.

fs.readFile('test.html', function read(err, data) { if (err) { console.log(err); } else { var msg = data.toString(); msg.replace("%name%", "myname"); msg.replace(/%email%/gi, ' example@gmail.com '); temp = "Hello %NAME%, would you like some %DRINK%?"; temp = temp.replace(/%NAME%/gi,"Myname"); temp = temp.replace("%DRINK%","tea"); console.log("temp: "+temp); console.log("msg: "+msg); } }); 

Exit:

 temp: Hello Myname, would you like some tea? msg: Hello %NAME%, would you like some %DRINK%? 
+6
source share
3 answers
 msg = msg.replace(/%name%/gi, "myname"); 

You pass a string instead of a regular expression for the first substitution, and that doesn't match because the case is different. Even if it matches, you do not reassign this changed value to msg . This is strange because you are doing everything right for tmp .

+11
source

You need to assign a variable to .replace() , which returns a string. In your case, you need to do, for example, msg = msg.replace("%name%", "myname");

the code:

 fs.readFile('test.html', function read(err, data) { if (err) { console.log(err); } else { var msg = data.toString(); msg = msg.replace("%name%", "myname"); msg = msg.replace(/%email%/gi, ' example@gmail.com '); temp = "Hello %NAME%, would you like some %DRINK%?"; temp = temp.replace(/%NAME%/gi,"Myname"); temp = temp.replace("%DRINK%","tea"); console.log("temp: "+temp); console.log("msg: "+msg); } }); 
+3
source

replace() returns a new line with replaced substrings, so you must assign it to a variable to access it. It does not change the original string.

You would like to write the converted string to your file.

+1
source

All Articles