Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / VBScript

VBScript HTML Encode

Rate me:
Please Sign up or sign in to vote.
2.20/5 (4 votes)
4 Feb 2009CPOL 76.7K   7   8
Server.HTMLEncode for VBScript (handles null strings)

Introduction

This function is a replacement for the Server.HTMLEncode method found in Classic ASP with one major difference... It accepts null strings without throwing errors!

The side effect is HTML Encoding for VBScript.

Background

I wrote this to overcome the common IsNull, IsNothing, IsEmpty string nightmare experienced when calling Server.HTMLEncode from Classic ASP.

Using the Code

VBScript
Function HTMLEncode(ByVal sVal)

    sReturn = ""

    If ((TypeName(sVal)="String") And (Not IsNull(sVal)) And (sVal<>"")) Then
    
        For i = 1 To Len(sVal)
        
            ch = Mid(sVal, i, 1)

            Set oRE = New RegExp : oRE.Pattern = "[ a-zA-Z0-9]"

            If (Not oRE.Test(ch)) Then
                ch = "&#" & Asc(ch) & ";"
            End If

            sReturn = sReturn & ch
            
            Set oRE = Nothing
        Next
    End If
    
    HTMLEncode = sReturn
End Function
VBScript
HTMLEncode("This is a & test!")

History

  • 4th February, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer MammothWorkwear.com
United Kingdom United Kingdom
Senior Web Developer, Systems Architect and Entrepreneur. Technical Director of MammothWorkwear.com. More information is available at http://www.johndoherty.info/

Comments and Discussions

 
GeneralMy vote of 1 Pin
Dave Kreskowiak19-Oct-09 11:44
mveDave Kreskowiak19-Oct-09 11:44 
GeneralMy vote of 1 [modified] Pin
Mark Cilia Vincenti12-Oct-09 5:14
Mark Cilia Vincenti12-Oct-09 5:14 
GeneralSome problems, some options Pin
mcnd5-Feb-09 4:31
mcnd5-Feb-09 4:31 
GeneralRe: Some problems, some options Pin
John Doherty5-Feb-09 5:16
John Doherty5-Feb-09 5:16 
GeneralRe: Some problems, some options Pin
Speednet_5-Feb-09 7:47
Speednet_5-Feb-09 7:47 
GeneralRe: Some problems, some options Pin
Saily25-Sep-14 10:33
Saily25-Sep-14 10:33 
GeneralOnly &lt; &gt; & and " characters Pin
Dominic Pettifer4-Feb-09 12:55
Dominic Pettifer4-Feb-09 12:55 
GeneralRe: Only &lt; &gt; & and " characters Pin
John Doherty4-Feb-09 23:43
John Doherty4-Feb-09 23:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.