简体   繁体   English

如何从 html 字符串中获取值?

[英]How to get Value from html string?

I have a html string like this which response from API:我有一个像这样的 html 字符串,它来自 API 的响应:

const response = `
<html>
  <head>
    <title></title>
  </head>
  <body>
     <code>Value I want to get<br></code>
  </body>
</html>
`;

So the content maybe dynamic but the tag <code> is unique.所以内容可能是动态的,但标签<code>是唯一的。 I want to have some more solutions on this to see what is the best solution.我想对此有更多的解决方案,看看什么是最好的解决方案。

You could use a DOMParser to convert your HTML string into a Document object which you can then use querySelector() to get your desired value:您可以使用DOMParser将您的 HTML 字符串转换为 Document 对象,然后您可以使用querySelector()来获取所需的值:

 const response = ` <html> <head> <title></title> </head> <body> <code>Value I want to get<br></code> </body> </html> `; const {body} = new DOMParser().parseFromString(response, 'text/html'); const value = body.querySelector('code').innerText; // find <code> tag and get text console.log(value);

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

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