Strip HTML from Text JavaScript

前端 未结 30 3573
北荒
北荒 2020-11-21 05:08

Is there an easy way to take a string of html in JavaScript and strip out the html?

30条回答
  •  死守一世寂寞
    2020-11-21 05:35

    If you're running in a browser, then the easiest way is just to let the browser do it for you...

    function stripHtml(html)
    {
       let tmp = document.createElement("DIV");
       tmp.innerHTML = html;
       return tmp.textContent || tmp.innerText || "";
    }
    

    Note: as folks have noted in the comments, this is best avoided if you don't control the source of the HTML (for example, don't run this on anything that could've come from user input). For those scenarios, you can still let the browser do the work for you - see Saba's answer on using the now widely-available DOMParser.

提交回复
热议问题