Jump to content

Coding Cookbook/HTML Encode

From Wikibooks, open books for an open world

Convert an object (commonly a string) to HTML-safe code.

VBScript solution

[edit | edit source]

Can convert strings and recordsets (converted to tables).

function HTMLEncode (vInput)
  dim i
  if IsNull(vInput) then 
    HTMLEncode = vInput
    exit function
    end if
  select case TypeName(vInput)
    case "Recordset"
      HTMLEncode = _
        "<table border='1'>" & vbNewLine & _
        "  <tr>"
      for i = 0 to vInput.Fields.Count - 1
        HTMLEncode = HTMLEncode & "<th>" & HTMLEncode(vInput.Fields.Item(i).Name) & "</th>"
        next
      HTMLEncode = HTMLEncode & "</tr>" & vbNewLine
      if not vInput.BOF then vInput.MoveFirst
      while not vInput.EOF
        HTMLEncode = HTMLEncode & "  <tr>"
        for i = 0 to vInput.Fields.Count - 1
          if IsNull(vInput.Fields.Item(i).Value) then
            HTMLEncode = HTMLEncode & "<td>&nbsp;</td>"
          else
            HTMLEncode = HTMLEncode & "<td>" & HTMLEncode(vInput.Fields.Item(i).Value) & "</td>"
            end if
          next
        HTMLEncode = HTMLEncode & "</tr>" & vbNewLine
        vInput.MoveNext
        wend
      if not vInput.BOF then vInput.MoveFirst
      HTMLEncode = HTMLEncode & _
        "</table>" & vbNewLine
    case else
      HTMLEncode = vInput
      HTMLEncode = Replace(HTMLEncode, chr(0), "")
      HTMLEncode = Trim(Server.HTMLEncode(HTMLEncode))
      HTMLEncode = Replace (HTMLEncode, "'", "&#39;")
      HTMLEncode = Replace (HTMLEncode, "<", "&lt;")
      HTMLEncode = Replace (HTMLEncode, ">", "&gt;")
      HTMLEncode = Replace (HTMLEncode, "  ", "&nbsp; ")
      HTMLEncode = Replace (HTMLEncode, chr(10), "<br>" )
    end select
  end function