javascript string.replace 在 node.js express 服务器中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13467981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
string.replace not working in node.js express server
提问by Damodaran
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.
我需要读取一个文件并用动态内容替换该文件中的一些文本。当我尝试 string.replace 时,它不适用于我从文件中读取的数据。但是对于它正在工作的字符串。我正在使用节点。 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, '[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%?
回答by Asad Saeeduddin
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
.
您将字符串而不是正则表达式传递给第一个替换,它不匹配,因为大小写不同。即使它确实匹配,您也不会将此修改后的值重新分配给msg
。这很奇怪,因为您对tmp
.
回答by Muthu Kumaran
You need to assign variable for .replace()
which returns the string. In your case, you need to do like, msg = msg.replace("%name%", "myname");
您需要为其分配.replace()
返回字符串的变量。在你的情况下,你需要这样做,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);
}
});
回答by alex
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.
replace()
返回一个带有替换子字符串的新字符串,因此您必须将其分配给一个变量才能访问它。它不会改变原始字符串。
You would want to write the transformed string back to your file.
您可能希望将转换后的字符串写回您的文件。