我需要更改 Node.js 中的 html。
1 我必须从日期中心读取日期
2 我必须在 NODE 中更改或添加 html 代码
实际上我需要读取日期并将其写入html文件
有 javascript 代码,我必须更改 html
var mysql = require("mysql");
var connection = mysql.createConnection({
host: 'localhost',
user: 'testuser',
password: 'a',
database: 'test',
port: 3306
});
connection.connect();
var read = connection.query("SELECT `Name` FROM `fruids`",function(error, result){
if(error) throw error;
console.log(result);
});
//~~~~~here i have to change inner
connection.end();
这是下面的html
<html>
<head>
<title>Регистрация</title>
<meta charset="utf-8" />
<style>
p{
text-align: right;
margin-right: 252px;
margin-top: -8px;
}
</style>
</head>
<body>
<h1>Введите данные</h1>
<form action="/register" method="post">
<label>Имя</label><br>
<input type="text" name="userName" /><br><br>
<label>Email</label><br>
<input type="text" name="userAge" /><br><br>
<label>Повідомлення</label><br>
<textarea type="text" name="userMess" ></textarea><br><br>
<input type="submit" value="OK" />
<input type="reset" value="Стерти" />
</form>
<form>
<h1 style="text-align: right;
margin-top: -284px;
margin-right: 170px;
">Повідомлення</h1>
<p class="inner" id="mesager">xss</p>
</form>
</body>
</html>
我可以做这样的事情吗
var date;
var node;
node.nodeValue = node.nodeValue.replace(/lol/, "<span>"+date+"</span>")
最佳答案
要在nodejs中编辑html,您可以使用cheerio
如果"lol"
是一个元素,替换它会非常简单:
let $ = require('cheerio').load(inputHtml)
$('lol').replaceWith(`<span>${date}</span>`)
但是,在您的问题中,您似乎需要替换文本匹配 /lol/
正则表达式 <span>[date]</span>
.
下面的代码通过迭代所有文本 Node 来实现此目的:
const $ = require('cheerio').load(inputHtml);
const getTextNodes=(elem)=>elem.type==='text'?[]:
elem.contents().toArray()
.filter(el=>el!==undefined)//I don't know why some elements are undefined
.reduce((acc, el)=>
acc.concat(...el.type==='text'?[el]:getTextNodes($(el))), [] )
let replaceRegex = /lol/;
let date = new Date().toLocaleDateString('en-US');
getTextNodes($(`html`))
.filter(node=>$.html(node).match(replaceRegex))
.map(node=>$(node).replaceWith($.html(node).replace(replaceRegex, `<span>${date}</span>`)) );
console.log($.html());
因此对于以下输入:
<html>
<head></head>
<body>
<p>This is some lol text</p>
Some other lol text
</body>
</html>
您将得到以下输出:
<html><head></head><body>
<p>This is some <span>3/18/2021</span> text</p>
Some other <span>3/18/2021</span> text
</body></html>
关于javascript - 如何在 Node.js 中更改或编辑 Html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60044369/