javascript - 获取两个 HTML 注释中间的内容
问题描述
我需要获取位于两个 HTML 注释中间的 HTML 内容。看代码:
<p>hello</p>
<!-- Write your comments here -->
<p>hello</p>
<!-- another comment -->
在这个例子中,我需要得到<p>Hello</p>
,我该怎么做?用正则表达式?谢谢阅读。
解决方案
您可以使用 XPath 表达式//comment()
来查找注释,循环它们以找到您关心的那些,然后循环从第一个节点开始,直到找到第二个。
const comments = document.evaluate("//comment()", document);
let start;
let end;
while (comment = comments.iterateNext()) {
if (comment.data.trim() === "Write your comments here") {
start = comment;
}
if (comment.data.trim() === "another comment") {
end = comment;
}
}
let current = start.nextSibling;
let matches = [];
while (current !== end) {
matches.push(current);
current = current.nextSibling;
}
console.log(matches.map(node => node.textContent));
<p>hello</p>
<!-- Write your comments here -->
<p>hello</p>
<!-- another comment -->
请注意,如果注释不是兄弟,这将中断,并且我没有进行任何错误处理。
推荐阅读
- python - sqlalchemy - 映射器映射类 X->y 无法为映射表 y 组装任何主键列
- asp.net-core - 关于托管在 Azure 应用服务横向扩展实例中的 Quartz.NET 的注意事项
- kdb - Q/KDB+ 通过查询创建新列
- azure-devops - 尽管项目在本地正确运行,但 Microsoft.CodeAnalysis 构建失败
- r - 如何在 Python 界面中运行 R 代码?
- video - markdown 中的 youtube 视频大小
- python - Pandas 在根据特定条件分配值时应用给出错误
- javascript - 如何从 JavaScript 中的元素列表填充表单字段?
- stack - 启动“xampp”堆栈时出错:我无法启动堆栈
- apache-spark - 无法在 Delta Lake 中分配内存