Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

javascript - How do I use JQuery to remove all "script" tags in a string of HTML?

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();

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...