2014年7月5日 星期六

ASP HtmlDecode 字串編碼轉換html

參考資料1:ASP Encode/Decode Functions

說明:當資料庫的資料儲存了換行的編碼,如:「 &#38;lt;br /&#38;gt;」(這是一個html換行的編碼)。那該如何轉換成html <br/>呢? 請看下列程式碼

程式碼
<%
Function HTMLDecode(sText)
    Dim I
    sText = Replace(sText, "&quot;", Chr(34))
    sText = Replace(sText, "&lt;"  , Chr(60)) '&lt 會被取代為 < 符號
    sText = Replace(sText, "&gt;"  , Chr(62)) '&gt 會被取代為 > 符號
    sText = Replace(sText, "&amp;" , Chr(38))
    sText = Replace(sText, "&nbsp;", Chr(32))
    For I = 1 to 255
        sText = Replace(sText, "&#" & I & ";", Chr(I)) '&#38 會被取代為 & 符號
    Next
    HTMLDecode = sText
End Function

Dim str_text
str_text="第一點&#38;lt;br /&#38;gt;第二點" '假設此變數為資料庫取出的資料
str_text=HTMLDecode(str_text) '呼叫第一次,此時回傳回來的值為「第一點&lt;br /&gt;第二點」
str_text=HTMLDecode(str_text) '呼叫第二次,此時回傳回來的值為「第一點<br />第二點」

Response.write str_text
%>

P.S 在傳統的ASP中沒有Server.HtmlDecode方法所以必須自行加入 HTMLDecode方法