Strip HTML from Text JavaScript

前端 未结 30 4173
北荒
北荒 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:38

    An improvement to the accepted answer.

    function strip(html)
    {
       var tmp = document.implementation.createHTMLDocument("New").body;
       tmp.innerHTML = html;
       return tmp.textContent || tmp.innerText || "";
    }
    

    This way something running like this will do no harm:

    strip("")
    

    Firefox, Chromium and Explorer 9+ are safe. Opera Presto is still vulnerable. Also images mentioned in the strings are not downloaded in Chromium and Firefox saving http requests.

提交回复
热议问题