Categories
JavaScript Answers

How to Extract the Text Out of HTML String Using JavaScript?

Spread the love

To extract the text out of HTML string using JavaScript, we can set the innerHTML property of an element to the HTML string.

Then we can use the textContent or the innerText property to get the text of the element.

For instance, we can write:

const extractContent = (s) => {
  const span = document.createElement('span');
  span.innerHTML = s;
  return span.textContent || span.innerText;
};

console.log(extractContent("<p>Hello</p><a href='http://example.org'>example</a>"))

to create the extractContent function that takes the s HTML string.

In the function, we call document.createElement to create the span element.

Then we set the innerHTML property of the span to s.

And finally, we return the textContent or innerText property to return the text content string.

Therefore, from the console log, we see 'Helloexample' logged.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.