Close Open HTML Tags in a String with VBScript (Without Using a Regular Expression) – CloseOpenHTMLTags.vbs

On more than one occasion I have wanted to pull a HTML text field from a database to populate a portion of a webpage. This is pretty common practice and really handy because you can update pages with forms.

This works really well except when you only want to pull just a portion of HTML text but not the whole thing. For example if you want to pull the first 100 or 200 characters to display as a summary. If the HTML you are truncating contains an open HTML tag it can really screw up the layout of the page.

Well, you really had two options when you wanted to rectify this situation. You could either remove all HTML formatting from the text using a regular expression (which sucked because you’d lose any links or images or styling that was embedded) or you could simply display the text as-is and hope that there were no tags open to screw up the layout of the rest of the page.

Well since both of those solutions weren’t really solutions at all, I decided to write a function that would parse the text of the HTML you pulled from the database and return a string with all the appropriate closing tags that you truncated earlier. (I actually use this script on my blog for the front page.)

This is really easier said than done. For one, there are tags in HTML that don’t have closing elements. The ones that I could think of off the top of my head br, img, input, meta, link, and hr are all included in the code below. It is pretty easy to add other tags that I missed by simply appending to the “sTagTypesToIgnore”. If you guys find any that I missed, please let me know and I will update the code below.

Also, blank spaces and extra information make figuring out what tag is what, more of a challenge.

For those that are really interested in how this code works, I have removed comments because they made the code twice as long. I will be posting the exact same code but with all of the commenting later. If you use this code, please give credit where credit is due and leave the copyright information. Thanks.


Leave a Comment