繁体   English   中英

正则表达式解析 html 以显示某些 id 标签

[英]Regex parse html to display certain id tags

我有一个需要解析的 html,只需要显示正在查询的 id。

例子:

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>
<h2 id="onlythisneedstobereturned"> hello </h2>
<p>My first paragraph.</p>

</body>
</html>

所以如果我给 id 为 "onlythisneedstobereturned" 它应该只返回 hello 。

我有一个正则表达式,它可以根据标签而不是 id 获取所有内容。 这是我的正则表达式

**myHtml.match("<h2(.|\n)*?<\/h2>")**

但我不确定如何使用特定的 id 标签进行正则表达式匹配。

你在这里不需要正则表达式,使用DOMParser像:

 const htmlStr = `<!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <h2 id="onlythisneedstobereturned"> hello </h2> <p>My first paragraph.</p> </body> </html>`; const parser = new DOMParser(); const doc = parser.parseFromString(htmlStr, "application/xml"); const content = doc.querySelector('#onlythisneedstobereturned').innerHTML; console.log(content);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM