Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 正则表达式解析html以显示某些id标记_Javascript_Html_Regex - Fatal编程技术网

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

Javascript 正则表达式解析html以显示某些id标记,javascript,html,regex,Javascript,Html,Regex,我有一个需要解析的html,只需要显示正在查询的id 例如: <!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <h2 id="onlythisneedstobereturned"> hello </h2> <p>My first paragraph.</p> </body> </html> 我的

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

例如:

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

我的第一个标题
你好
我的第一段

所以,如果我把id设为“onlythissneedstobereturned”,它应该只返回hello

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

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

**myHtml.match(“此处不需要正则表达式,请使用:

const htmlStr=`
我的第一个标题
你好
我的第一段

`; const parser=new DOMParser(); const doc=parser.parseFromString(htmlStr,“应用程序/xml”); const content=doc.querySelector(“#仅需要返回”).innerHTML;
console.log(content);
直接使用
document.querySelector(“#仅需要返回此选项”)怎么样.innerHTML
?为什么需要将HTML解析为字符串?此代码是在浏览器中运行还是在NodeJS中运行?如果是在浏览器中,则可以使用DOM来执行此操作。如果是字符串,则可以从中创建DOMFragment并使用
querySelector