Asp.Net將字符串轉為區碼位編碼,或者將區碼位編碼字符串轉為對應的字符串內容。
數字;這種編碼其實就是將單個字符轉為對應的區碼位(數字),然後區碼位前綴加上“”,後綴加上“;”組成,對於這種編碼的字符串,浏覽器會自動解析為對應的字符。
Asp.Net字符串和編碼轉換源代碼和測試代碼如下:
using System; using System.Text.RegularExpressions; public partial class purchase_property : System.Web.UI.Page { /// <summary> /// Asp.Net將字符串轉為16進制區碼位編碼 /// </summary> /// <param name="s">要進行16進制區碼位編碼的字符串</param> /// <returns>編碼後的16進制區碼位字符串</returns> public string StringToUnicodeCodeBit(string s) { if (string.IsNullOrEmpty(s) || s.Trim() == "") return ""; string r = ""; for (int i = 0; i < s.Length; i++) r += "" + ((int)s[i]).ToString() + ";"; return r; } public string reMatchEvaluator(Match m) { return ((char)int.Parse(m.Groups[1].Value)).ToString(); } /// <summary> /// Asp.Net將16進制區碼位編碼轉為對應的字符串 /// </summary> /// <param name="s">16進制區碼位編碼的字符串</param> /// <returns>16進制區碼位編碼的字符串對應的字符串</returns> public string UnicodeCodeBitToString(string s) { if (string.IsNullOrEmpty(s) || s.Trim() == "") return ""; Regex rx = new Regex(@"(\d+);", RegexOptions.Compiled); return rx.Replace(s, reMatchEvaluator); } protected void Page_Load(object sender, EventArgs e) { string s = "Asp.Net區碼位字符串"; s = StringToUnicodeCodeBit(s);//轉為編碼 Response.Write(s); Response.Write("\n"); s = UnicodeCodeBitToString(s);//編碼轉為字符串 Response.Write(s); } }
javascript版本可以參考下面:
function uncode(str) {//把編碼轉換成字符 return str.replace(/(x)?([^&]{1,5});?/g, function (a, b, c) { return String.fromCharCode(parseInt(c, b ? 16 : 10)); }); } function encode(str) {//把字符轉換成編碼 var a = [], i = 0; for (; i < str.length; ) a[i] = str.charCodeAt(i++); return "" + a.join(";") + ";"; }