js 中文转义

javascript:

<script>   
  test = "转义字符"  
  str = ""     
  for( i=0;i<test.length; i++ )  
  {       temp = test.charCodeAt(i).toString(16);  
  str    += "\\u"+ new Array(5-String(temp).length).join("0") +temp;  
  }  
  document.write (str)
  alert(eval("'"+str+"'"));
  </script>

c#:

 string str = "转义字符";
            string outStr = "";
            if (!string.IsNullOrEmpty(str))
            {
                for (int i = 0; i < str.Length; i++)
                {
                    outStr += "\\u" + ((int)str[i]).ToString("x");
                }
            }
            Console.WriteLine(outStr);
            string str2 = @"\u8f6c\u4e49\u5b57\u7b26";
            string outStr2 = "";
            if (!string.IsNullOrEmpty(str2))
            {
                string[] strlist = str2.Replace(@"\", "").Split('u');
                try
                {
                    for (int i = 1; i < strlist.Length; i++)
                    {
                      
                        outStr2 += (char)int.Parse(strlist[i], System.Globalization.NumberStyles.HexNumber);
                    }
                    Console.WriteLine(outStr2);
                }
                catch (FormatException ex)
                {
                    outStr2 = ex.Message;
                    Console.WriteLine("errot:"+outStr2);
                }
            }  

 

posted @ 2013-04-01 09:27  小川丶  阅读(4385)  评论(0编辑  收藏  举报