string.replace not working in node.js express server

18,235

Solution 1

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.

Solution 2

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, '[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);
    }
});

Solution 3

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.

Share:
18,235
Damodaran
Author by

Damodaran

My LinkedIn Profile My Blog Twitter: @damodaranp Damodaran P

Updated on June 15, 2022

Comments

  • Damodaran
    Damodaran almost 2 years

    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%?