Strip HTML from Text JavaScript

前端 未结 30 3594
北荒
北荒 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

    I would like to share an edited version of the Shog9's approved answer.


    As Mike Samuel pointed with a comment, that function can execute inline javascript codes.
    But Shog9 is right when saying "let the browser do it for you..."

    so.. here my edited version, using DOMParser:

    function strip(html){
       let doc = new DOMParser().parseFromString(html, 'text/html');
       return doc.body.textContent || "";
    }
    

    here the code to test the inline javascript:

    strip("")
    

    Also, it does not request resources on parse (like images)

    strip("Just text ")
    

提交回复
热议问题