Remove HTML and XML tags from string in Javascript

When you want to get the raw text from a string but it included the HTML or XML tags like this case:

const stringExample = "<div>This is your <b>text</b></div>";
// you only want to get "This is content" without div and b tag

Copy this code

We can do that easy with the function bellow:

const getNoHTMLContents = htmlString => {
  const div = document.createElement('div');
  div.innerHTML = htmlString;
  return div.textContent || div.innerText || '';

// usage
const stringExample = "<div>This is your <b>text</b></div>";
console.log(getNoHTMLContents(stringExample)); // Result: This is your text

Copy this code


In the function above, we create a new wrapper element (div) with createElement method and use the innerHTML method to render the HTML string then get raw text content by textContent or innerText method.

© 2019 4codev

Created with love by Sil.