string.replace not working in node.js express server
msg = msg.replace(/%name%/gi, "myname");
You're passing a string instead of a regex to the first replace, and it doesn't match because the case is different. Even if it did match, you're not reassigning this modified value to msg
. This is strange, because you're doing everything correctly for tmp
.
You need to assign variable for .replace()
which returns the string. In your case, you need to do like, msg = msg.replace("%name%", "myname");
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); }});
replace()
returns a new string with the replaced substrings, so you must assign that to a variable in order to access it. It does not mutate the original string.
You would want to write the transformed string back to your file.