I need to read a file and replace some texts in that file with dynamic content.when i tried string.replace it is not working for the data that i read from the file.But for the string it is working.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, '[email protected]');
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);
}
});
Output:
temp: Hello Myname, would you like some tea?
msg: Hello %NAME%, would you like some %DRINK%?
Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.
The "replaceAll" is not a function error occurs when we call the replaceAll() method on a value that is not of type string, or in a browser that doesn't support the method. To solve the error, only call the replaceAll() method on strings in supported browsers.
The replaceAll() method will substitute all instances of the string or regular expression pattern you specify, whereas the replace() method will replace only the first occurrence.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With