简体   繁体   中英

Remove <script> tags from a string along with the content between them

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?

Any help would be much appreciated!

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>"

Try this:-

var str= "<script>blah blah blah</script><div>blah blah blah</div>";
var html = $(str.bold()); 
html.find('script').remove();

Like so:

var div = $('<div>').html(str);

div.find('script').remove();

str = div.html();

Example: http://codepen.io/paulroub/pen/IabsE

Here is a fiddle ( https://jsfiddle.net/skoley/9dnmbj3d/ ) of the answers which works best taken from several other sources, credit goes to them.

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;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM