Strip HTML from Text JavaScript

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

    Here's a version which sorta addresses @MikeSamuel's security concern:

    function strip(html)
    {
       try {
           var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
           doc.documentElement.innerHTML = html;
           return doc.documentElement.textContent||doc.documentElement.innerText;
       } catch(e) {
           return "";
       }
    }
    

    Note, it will return an empty string if the HTML markup isn't valid XML (aka, tags must be closed and attributes must be quoted). This isn't ideal, but does avoid the issue of having the security exploit potential.

    If not having valid XML markup is a requirement for you, you could try using:

    var doc = document.implementation.createHTMLDocument("");
    

    but that isn't a perfect solution either for other reasons.

提交回复
热议问题