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(";") + ";"; }