Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.replace not working in node.js express server

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%?
like image 358
Damodaran Avatar asked Nov 20 '12 06:11

Damodaran


People also ask

How do you replace a character in a string in node js?

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.

Why is replaceAll not working JavaScript?

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.

Does string replace replace all instances?

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.


1 Answers

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.

like image 133
Asad Saeeduddin Avatar answered Oct 17 '22 19:10

Asad Saeeduddin