A quick jQuery solution for stripping XHTML tags from a string, except for a specific tag.

Posted 5 months ago in Programming

I have a bunch of divs throughout a page, and I don't control where the content comes from. I want to be sure those divs contain no XHTML, except for <p> tags.

A simple jQuery solution should do the trick.

With this code, any element with class 'sanitize' will be taken care of:

$('.sanitize').each(function() {
    $(this).html(
        $(this).html().replace(/\<\/?[^p ]{1,2}[^>]*>/ig,'')
    )
});

If you needed to retain some tag other than <p>, you could simply modify this portion of the RegEx:

[^p ]

...where 'p' is the name of the tag.

Thanks to Jon for his RegEx mastery, and Pete for his jQuery shenanigans.

3 Comments

5 months ago

Would multiple tag exclusion be like:

[^p|^a|^table]

?

5 months ago

Jon says: "This doesn't eliminate the <param> tags."

5 months ago

@Pete Karl II, yes, I do believe so.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options