I’ve been playing a bit with regular expressions lately and have to find some
useful tasks in order to practice the skill. So, today I wanted to make a little method
that strips HTML comments from an ASP.NET webpage at runtime. The practical use of
the exercise is somewhat limited for most developers, but some websites have so many
comments that it might just save a decent amount of bytes from the response stream.
to hide it’s workings from older browsers. That would mean that those script tags
the HTML comments correctly. Some don’t so you have to change it your self.
The commenting should look like this which is also the right way to do it.
The regular expression is very simple and all you need to do is to add the following
method to your webpage, user control or master page.
private static Regex _Regex
= new Regex("((<!--
)((?!<!-- ).)*( -->))(\\r\\n)*", RegexOptions.Singleline);
protected override void Render(HtmlTextWriter writer)
using (StringWriter sw
= new StringWriter())
using (HtmlTextWriter htmlWriter
= new HtmlTextWriter(sw))
Maybe not the most useful stuff I've ever written, but fine for learning. The only
>* $4.95/month ASP.NET Hosting with FREE SQL 2012 DB! – Click Here!