Strip HTML from Text JavaScript

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

    As an extension to the jQuery method, if your string might not contain HTML (eg if you are trying to remove HTML from a form field)

    jQuery(html).text();
    

    will return an empty string if there is no HTML

    Use:

    jQuery('

    ' + html + '

    ').text();

    instead.

    Update: As has been pointed out in the comments, in some circumstances this solution will execute javascript contained within html if the value of html could be influenced by an attacker, use a different solution.

提交回复
热议问题