Asp.Net將字符串轉為&#區碼位編碼,或者將&#區碼位編碼字符串轉為對應的字符串內容。
&#數字;這種編碼其實就是將單個字符轉為對應的區碼位(數字),然后區碼位前綴加上“&#”,后綴加上“;”組成,對于這種編碼的字符串,瀏覽器會自動解析為對應的字符。
Asp.Net字符串和&#編碼轉換源代碼和測試代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
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版本可以參考下面:
1
2
3
4
5
6
7
8
9
10
|
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( ";&#" ) + ";" ; } |