【问题标题】:How to replace all html code of the <body> tag with NodeJS?如何用 NodeJS 替换 <body> 标签的所有 html 代码?
【发布时间】:2017-02-28 06:39:14
【问题描述】:

基于:https://stackoverflow.com/a/14181136/3363138我做了相应的修改:

var fs = require('fs')
var desired_code = '<div>Desired Code</div>'

fs.readFile(file.html, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }

  //Here I need to load all the body tag content, but how?
  var result = data.replace(<body>html tags to be replaced</body>, desired_code);

  fs.writeFile(file.html, result, 'utf8', function (err) {
     if (err) return console.log(err);
  });
});

在这个功能上我需要加载所有的body标签内容,但是我该怎么做呢?

var result = data.replace(<body>html tags to be replaced</body>, desired_code);

【问题讨论】:

    标签: html node.js filesystems


    【解决方案1】:

    如果你想在 html 代码中更改字符串,我现在看到两个选项:

    • 您为此编写了一个正则表达式(简单、快速,但不太干净和安全);
    • 您使用像cheerio.js 这样的html 解析器,更改您的节点“body”并进行字符串化(更复杂但更安全、更简洁)。

    对于第一个选项,类似于: data = data.replace(/&lt;body&gt;(.*)&lt;\/body&gt;/, '&lt;div&gt;Hello world&lt;/div&gt;');

    对于第二个选项,类似:

    parsed = cheerio.parse(data); parsed.find('body').html('<div>Hello world</div>'); data = cheerio.html();

    【讨论】:

    • 加一个,但我不同意正则表达式选项
    • 谢谢。这个正则表达式对我有用:/(.|\n)*?/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    相关资源
    最近更新 更多