string.replace不能在node.js express服务器上工作
我需要阅读一个文件,并用该dynamic内容replace该文件中的一些文本。当我尝试string.replace它不工作的数据,我从文件读取。但string它正在working.I使用节点。 js和快递。
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, '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); } });
输出:
temp: Hello Myname, would you like some tea? msg: Hello %NAME%, would you like some %DRINK%?
msg = msg.replace(/%name%/gi, "myname");
你传递一个string而不是一个正则expression式到第一个replace,并且它不匹配,因为情况是不同的。 即使它匹配,你也不会把这个修改后的值重新分配给msg
。 这很奇怪,因为你正在为tmp
正确地做所有事情。
您需要为.replace()
分配返回string的variables。 在你的情况下,你需要这样做, msg = msg.replace("%name%", "myname");
码:
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()
用被replace的子string返回一个新的string,所以你必须把它赋值给一个variables来访问它。 它不会改变原始string。
你会想把转换后的string写回你的文件。