假设我有一串 HTML 代码。我想使用 JQuery 删除所有 <script>
字符串中的标签。
我该怎么做?
注意:我想使用 JQuery 而不是 REGEX 来执行此操作。
这个有用吗? $(var).find('script').remove();
最佳答案
这应该适合你:
var stringOfHtml = // your string here
$(stringOfHtml).find('script').remove();
要获取删除了脚本标签的新字符串:
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 - 必须使用 p 而不是脚本,因为脚本破坏了 fiddle ,但原理相同。
实际工作答案在这里(希望如此)
这是脚本问题的解决方法,使用 replace 将脚本文本与其他内容交换(尝试使其唯一)然后删除这些新标签并再次使用 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'));
关于javascript - 如何使用 JQuery 删除 HTML 字符串中的所有 "script"标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8503560/