Javascript Clean HTML
>> Tuesday, April 24, 2012
Normally when using WYSIWYG editors liks CKEditor, you allow the user to enter poorly formatted HTML, this isn't really a big issue most of the time, but you have to be very careful with this, for example, if you allow them to enter any html, they could easily send a
tag with a custom request, and XSS injection.
This isn't about security but a little help with managing the generated HTML, I needed a function to clean empty tags, thanks to the awesomeness of Regular Expressions, I ended up with this little guy
String.prototype.htmlTrim = function () { return this.replace(/<(p|div|span|b|u|i|strong|em|h\d+)>\s*\n*\t*[ ]*\s*\n*\t*<\/\1>/, ''); };
That will clean all empty tags, but it won't fix much more. Anyways! I think this might be helpful for some people so I'm sharing it here.
Usage is
myString.htmlTrim();