javascript 从字符串中删除 <script> 标签以及它们之间的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18664536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove <script> tags from a string along with the content between them
提问by barrettathome
I have looked and looked and looked but I couldn't find anything on this. So lets say I have this string...
我已经看了又看,但我找不到任何关于这个的东西。所以可以说我有这个字符串......
var str = '<script>blah blah blah</script><a>...</a><div>...</div><p>...</p>';
I need to strip out the script tags out of the string along with all the content between the tags. Once the script tag is stripped I need to append it to a textarea. How in the world do I do this with jQuery?
我需要从字符串中去除脚本标签以及标签之间的所有内容。一旦脚本标签被剥离,我需要将它附加到一个文本区域。我到底如何用 jQuery 做到这一点?
Any help would be much appreciated!
任何帮助将非常感激!
回答by dandavis
since nobody else is going to post a simple and reliably-working routine, i guess i will:
由于没有其他人会发布一个简单且可靠的例程,我想我会:
function noscript(strCode){
var html = $(strCode.bold());
html.find('script').remove();
return html.html();
}
alert( noscript("<script>blah blah blah</script><div>blah blah blah</div>") );
//shows: "<div>blah blah blah</div>"
回答by Rahul Tripathi
Try this:-
试试这个:-
var str= "<script>blah blah blah</script><div>blah blah blah</div>";
var html = $(str.bold());
html.find('script').remove();
回答by Paul Roub
Like so:
像这样:
var div = $('<div>').html(str);
div.find('script').remove();
str = div.html();
Example: http://codepen.io/paulroub/pen/IabsE
回答by skoley
Here is a fiddle ( https://jsfiddle.net/skoley/9dnmbj3d/) of the answers which works best taken from several other sources, credit goes to them.
这是从其他几个来源获得的最佳答案的小提琴(https://jsfiddle.net/skoley/9dnmbj3d/),归功于他们。
function noscript(strCode){
var html = $(strCode.italics());
html.find('script').remove();
return html.html();
}
function noscript_alt(str)
{
var div = $('<div>').html(str);
div.find('script').remove();
str = div.html();
return str;}