简体   繁体   中英

Remove HTML content groups from start to end of string in JavaScript

I need a regex that could remove the full tag from start to end.
For eg.:
For the given string:

var str = "Hello <script> console.log('script tag') </script> World";

I need an output:

"Hello  World" // with full script tag including inner content removed

I am very specific for only the RegEx solution, so don't need browser append tricks.
Kindly notify if this is not possible at all.

I tried this and its variations:

inputString.replace( /<\/?[^>]+(>|$)/g, "" );

But this is not achieving what I want and is removing only the tag elements, leaving the inner content. What RegEx groups should I create in the expression?

I do not need to address stuff like type="text/javascript" , as they are already filtered before I receive the string. No jQuery plz. (I need to store the RegEx as a property to my filter object).

Help appreciated.

This is pure regex solution:

var str = "Hello <script> console.log('script tag') </script> World";
var repl = str.replace(/<([^.]+)>.*?<\/\1>/ig, '');
//=> "Hello  World"

with an assumption that there is no < OR > between opening and closing tags.

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