Hoang Subin
Hoang Subin

Reputation: 7400

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.

Upvotes: 4

Views: 2983

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50684

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);

Upvotes: 9

Related Questions