How do I use JQuery to remove all “script” tags in a string of HTML?

后端 未结 4 429
离开以前
离开以前 2020-12-09 04:15

Suppose I have a string of HTML code. I want to use JQuery to remove all

4条回答
  •  庸人自扰
    2020-12-09 04:46

    This should work for you:

    var stringOfHtml = // your string here
    $(stringOfHtml).find('script').remove();
    

    To get the new string with the script tags removed:

    var stringOfHtml = "
    "; var html = $(stringOfHtml); html.find('script').remove(); var stringWithoutScripts = html.wrap("
    ").parent().html(); // have to wrap for html to get the outer element

    JS Fiddle Example - Had to use p instead of script as script broke the fiddle, same principle though.

    Actual working answer here (hopefully)

    Here is a workaround for the script issue, use replace to swap the script text with something else (try and make it unique) then remove those new tags and use replace again to swap back in case script is used anywhere else in text. Yes, it does use regex, but not to remove the script tags so I'm hoping that's alright ;):

    var stringOfHtml = "

提交回复
热议问题