Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Value from html string?

I have a html string like this which response from 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. I want to have some more solutions on this to see what is the best solution.

like image 994
Tran Son Hoang Avatar asked Jan 01 '23 11:01

Tran Son Hoang


1 Answers

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:

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);
like image 56
Nick Parsons Avatar answered Jan 08 '23 00:01

Nick Parsons