js和java转码

转为ASCII形式:

Java代码

 

String str="你是";
  try {
   System.out.println(URLEncoder.encode(str, "UTF-8"));  //结果为你是
   System.out.println(URLDecoder.decode("你是","UTF-8"));  //结果为你是     这个里面的字符为URLEncoder.encode(str, "UTF-8")产生
   System.out.println(URLDecoder.decode("你是","UTF-8"));  //结果为你是     这个里面的字符为javascript中encodeURI('你是')产生
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }

HTML中的Js代码:

 <script type="text/javascript">
   function test_encodeURI(){
   alert(encodeURI('你是')); // 到jsp页面中解码的话用URLDecoder.decode即可,具体参看类URLEncodeTest.java
   document.write(encodeURI('你是')+"<br>");
   alert(decodeURI('你是')); // encodeURIComponent
   document.write(encodeURI('www.cup.edu.cn')+"<br>");
   document.write(encodeURIComponent('http://www.cup.edu.cn')+"<br>");   //http://www.cup.edu.cn
   document.write(decodeURI('www.cup.edu.cn')+"<br>");
   document.write(decodeURIComponent('http://www.cup.edu.cn')+"<br>");  //http://www.cup.edu.cn
   }
</script>


<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;
         }

你可能感兴趣的:(js和java转码)