我有一个这样的html字符串,它来自API:
const response = `
<html>
<head>
<title></title>
</head>
<body>
<code>Value I want to get<br></code>
</body>
</html>
`;
Run Code Online (Sandbox Code Playgroud)
因此,内容可能是动态的,但标签<code>
是唯一的。我希望对此有更多解决方案,以了解最佳解决方案。
您可以使用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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
53 次 |
最近记录: |