[英]How do I use JQuery to remove all “script” tags in a string of HTML?
Suppose I have a string of HTML code.假设我有一串 HTML 代码。 I want to use JQuery to remove all
<script>
tags from the string.我想使用 JQuery 从字符串中删除所有
<script>
标签。
How can I do that?我怎样才能做到这一点?
Note: I want to use JQuery , not REGEX, to do this.注意:我想使用 JQuery 而不是 REGEX 来做到这一点。
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. JS 小提琴示例- 必须使用 p 而不是脚本,因为脚本破坏了小提琴,但原理相同。
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'));
Old question, but if you are still looking for the easiest way to remove scripts from a string try老问题,但如果您仍在寻找从字符串中删除脚本的最简单方法,请尝试
$.parseHTML(string);
$.parseHTML() automatically removes script tags from strings. $.parseHTML() 自动从字符串中删除脚本标签。
Edit:编辑:
This works because keepScripts
has false value as default.这是有效的,因为
keepScripts
默认值为 false。 (Reference: $.parseHtml ) (参考: $.parseHtml )
$.parseHTML(data, context, keepScripts)
i guess this should work我想这应该有效
$('script').each(function () {
$(this).remove();
});
Here is the other solution if one want to remove script tag from any string:如果要从任何字符串中删除脚本标记,这是另一种解决方案:
var str = "<script>Content...</script>"
use var afterstring = str.replace("<script>","new");
and afterstring = str.replace("<\/script>","new");
Hope it will work for you !希望它对你有用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.