[英]How to replace all html code of the <body> tag with NodeJS?
Based on: https://stackoverflow.com/a/14181136/3363138 I did the corresponded modifications: 基于: 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);
});
});
On this function I need to load all the body tag content, but how can I do it? 在此功能上,我需要加载所有正文标签内容,但是我该怎么做呢?
var result = data.replace(<body>html tags to be replaced</body>, desired_code);
If you want to change something in html code that is String, I see two options now : 如果您想更改html代码中的String,那么现在可以看到两个选项:
For the first option, something like : data = data.replace(/<body>(.*)<\\/body>/, '<div>Hello world</div>');
对于第一个选项,类似于:
data = data.replace(/<body>(.*)<\\/body>/, '<div>Hello world</div>');
For the second option, something like : 对于第二个选项,类似:
parsed = cheerio.parse(data); parsed.find('body').html('<div>Hello world</div>'); data = cheerio.html();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.