JS中的UniCode轉碼問題


<script type="text/javascript">
        var GB2312UnicodeConverter = {
            ToUnicode: function (str) {
                return escape(str).toLocaleLowerCase().replace(/%u/gi, '\\u');
            }
            , ToGB2312: function (str) {
                return unescape(str.replace(/\\u/gi, '%u'));
            }
        };

        var str = '上海', unicode;
        document.write(str + '<br/>');
        unicode = GB2312UnicodeConverter.ToUnicode(str);
        document.write('漢字轉換為Unicode代碼:' + unicode + '<br/><br/>');
        document.write('Unicode代碼轉換為漢字:' + GB2312UnicodeConverter.ToGB2312(unicode));
    </script>

  

/// <summary>
        /// 漢字轉換為Unicode編碼
        /// </summary>
        /// <param name="str">要編碼的漢字字符串</param>
        /// <returns>Unicode編碼的的字符串</returns>
        public static string ToUnicode(string str)
        {
            byte[] bts = Encoding.Unicode.GetBytes(str);
            string r = "";
            for (int i = 0; i < bts.Length; i += 2) r += "\\u" + bts[i + 1].ToString("x").PadLeft(2, '0') + bts[i].ToString("x").PadLeft(2, '0');
            return r;
        }
        /// <summary>
        /// 將Unicode編碼轉換為漢字字符串
        /// </summary>
        /// <param name="str">Unicode編碼字符串</param>
        /// <returns>漢字字符串</returns>
        public static string ToGB2312(string str)
        {
            string r = "";
            MatchCollection mc = Regex.Matches(str, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            byte[] bts = new byte[2];
            foreach (Match m in mc)
            {
                bts[0] = (byte)int.Parse(m.Groups[2].Value, NumberStyles.HexNumber);
                bts[1] = (byte)int.Parse(m.Groups[1].Value, NumberStyles.HexNumber);
                r += Encoding.Unicode.GetString(bts);
            }
            return r;
        }

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM