Noob Noob - 3 months ago 7
HTML Question

Html.Replace is not working in Node

I have following code:

http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
var html=fs.readFileSync(__dirname +'/index.htm','utf8');
var message='Template';
html.replace('{Message}',message);
res.end(html);

}).listen(1337,'127.0.0.1');


And below id html file in which I want to replace
{Message},
but its not working.

<!DOCTYPE html>
<html>
<body>

<h1>{Message}</h1>

</body>
</html>


This is what I get while debugging:

Screenshot

Answer

From the MDN docs for String.prototype.replace():

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

This means that your original string will remain unchanged, and the call to replace() will return a new string with the replacement made.

Try updating your code with this line:

html = html.replace('{Message}',message);
Comments