且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何使用JQuery删除所有“脚本”一串HTML中的标签?

更新时间:2023-12-05 18:37:52



  var stringOfHtml = //你的字串在这里
$(stringOfHtml) 。.find( '脚本')除去();

使用脚本标记去除新字符串:

  < 
var html = $(stringOfHtml);
html.find('script')。remove();

var stringWithoutScripts = html.wrap(< div>)。parent()。html(); //必须包装html以获得外部元素

- 不得不使用脚本来代替脚本,因为脚本破坏了小提琴,尽管如此。



实际工作答案在这里(希望)



以下是脚本问题的解决方法,使用replace将脚本文本与其他内容交换(尝试并使其唯一),然后删除这些新标签,并在文本中的任何其他位置使用脚本时再次使用替换替换。是的,它确实使用了正则表达式,但不能删除脚本标签,所以我希望这是好的;):

  var stringOfHtml =< p>< / p>< script> alert('fail');< / scr+ipt>< span>< / span>; 
var wrappedString ='< div>'+ stringOfHtml +'< / div>';
var noScript = wrappedString.replace(/ script / g,THISISNOTASCRIPTREALLY);
var html = $(noScript);
html.find('THISISNOTASCRIPTREALLY')。remove();

alert(html.html()。replace(/ THISISNOTASCRIPTREALLY / g,'script'));

JS Fiddle解决方法



JS小提琴示例与脚本文本


Suppose I have a string of HTML code. I want to use JQuery to remove all <script> tags from the string.

How can I do that?

Note: I want to use JQuery , not REGEX, to do this.

Does this work? $(var).find('script').remove();

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 = "<div><script></script><span></span></div>";
var html = $(stringOfHtml);
html.find('script').remove();

var stringWithoutScripts = html.wrap("<div>").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 = "<p></p><script>alert('fail');</scr" + "ipt><span></span>";
var wrappedString = '<div>' + stringOfHtml + '</div>';
var noScript = wrappedString.replace(/script/g, "THISISNOTASCRIPTREALLY");
var html = $(noScript);
html.find('THISISNOTASCRIPTREALLY').remove();

alert(html.html().replace(/THISISNOTASCRIPTREALLY/g, 'script'));

JS Fiddle Workaround

JS Fiddle Example With Script Text