Asp.Net將字符串轉(zhuǎn)為&#區(qū)碼位編碼,或者將&#區(qū)碼位編碼字符串轉(zhuǎn)為對(duì)應(yīng)的字符串內(nèi)容。
&#數(shù)字;這種編碼其實(shí)就是將單個(gè)字符轉(zhuǎn)為對(duì)應(yīng)的區(qū)碼位(數(shù)字),然后區(qū)碼位前綴加上“&#”,后綴加上“;”組成,對(duì)于這種編碼的字符串,瀏覽器會(huì)自動(dòng)解析為對(duì)應(yīng)的字符。
Asp.Net字符串和&#編碼轉(zhuǎn)換源代碼和測(cè)試代碼如下:
01 using System;
02 using System.Text.RegularExpressions;
03 public partial class purchase_property : System.Web.UI.Page
04 {
05 /// <summary>
06 /// Asp.Net將字符串轉(zhuǎn)為16進(jìn)制區(qū)碼位&#編碼
07 /// </summary>
08 /// <param name="s">要進(jìn)行16進(jìn)制區(qū)碼位編碼的字符串</param>
09 /// <returns>編碼后的16進(jìn)制區(qū)碼位&#字符串</returns>
10 public string StringToUnicodeCodeBit(string s)
11 {
12 if (string.IsNullOrEmpty(s) || s.Trim() == "") return "";
13 string r = "";
14 for (int i = 0; i < s.Length; i++) r += "&#" + ((int)s[i]).ToString() + ";";
15 return r;
16 }
17 public string reMatchEvaluator(Match m)
18 {
19 return ((char)int.Parse(m.Groups[1].Value)).ToString();
20 }
21 /// <summary>
22 /// Asp.Net將16進(jìn)制區(qū)碼位&#編碼轉(zhuǎn)為對(duì)應(yīng)的字符串
23 /// </summary>
24 /// <param name="s">16進(jìn)制區(qū)碼位編碼的字符串</param>
25 /// <returns>16進(jìn)制區(qū)碼位編碼的字符串對(duì)應(yīng)的字符串</returns>
26 public string UnicodeCodeBitToString(string s)
27 {
28 if (string.IsNullOrEmpty(s) || s.Trim() == "") return "";
29 Regex rx = new Regex(@"&#(\d+);", RegexOptions.Compiled);
30 return rx.Replace(s, reMatchEvaluator);
31 }
32 protected void Page_Load(object sender, EventArgs e)
33 {
34 string s = "Asp.Net區(qū)碼位字符串";
35 s = StringToUnicodeCodeBit(s);//轉(zhuǎn)為&#編碼
36 Response.Write(s);
37 Response.Write("\n");
38 s = UnicodeCodeBitToString(s);//&#編碼轉(zhuǎn)為字符串
39 Response.Write(s);
40 }
41 }
javascript版本可以參考下面:
01 function uncode(str) {//把&#編碼轉(zhuǎn)換成字符
02 return str.replace(/&#(x)?([^&]{1,5});?/g, function (a, b, c) {
03 return String.fromCharCode(parseInt(c, b ? 16 : 10));
04 });
05 }
06 function encode(str) {//把字符轉(zhuǎn)換成&#編碼
07 var a = [], i = 0;
08 for (; i < str.length; ) a[i] = str.charCodeAt(i++);
09 return "&#" + a.join(";&#") + ";";
10 }
更多信息請(qǐng)查看IT技術(shù)專(zhuān)欄