【问题标题】:string.replace not working in node.js express serverstring.replace 在 node.js express 服务器中不起作用
【发布时间】:2012-11-08 05:05:11
【问题描述】:

我需要读取一个文件并用动态内容替换该文件中的一些文本。当我尝试 string.replace 时,它​​不适用于我从文件中读取的数据。但是对于它正在工作的字符串。我是使用 node.js 和 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, '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%?

【问题讨论】:

    标签: javascript string file node.js express


    【解决方案1】:
    msg = msg.replace(/%name%/gi, "myname");
    

    您将字符串而不是正则表达式传递给第一个替换,它不匹配,因为大小写不同。即使匹配,您也不会将此修改后的值重新分配给msg。这很奇怪,因为您为 tmp 所做的一切都是正确的。

    【讨论】:

      【解决方案2】:

      您需要为返回字符串的.replace() 分配变量。在你的情况下,你需要这样做,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);
          }
      });
      

      【讨论】:

      • simple.toString() 来救援。所有其他答案都忽略了这种出色的简单性。
      【解决方案3】:

      replace() 返回带有替换子字符串的新字符串,因此您必须将其分配给变量才能访问它。它不会改变原始字符串。

      您可能希望将转换后的字符串写回您的文件。

      【讨论】:

        猜你喜欢
        • 2017-04-29
        • 2018-05-15
        • 2018-07-17
        • 2011-11-27
        • 1970-01-01
        • 1970-01-01
        • 2014-07-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多