zoukankan      html  css  js  c++  java
  • 封装JS String对汉字编码进行相互转换处理

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
    <title>无标题文档</title> 
    </head> 
    <script> 

    String.prototype.ulength = function () {    
        var c, b = 0, l = this.length;    
        while(l) {    
            c = this.charCodeAt(--l);    
            b += (c < 128) ? 1 : ((c < 2048) ? 2 : ((c < 65536) ? 3 : 4));    
        };    
        return b;    

    String.prototype.cnStringToAscii = function() {//汉字转换ascii 
        return escape(this).replace(/%u/g, '\&#x'); 
    }; 
    String.prototype.cnStringToUnicode = function() {//汉字转换unicode 
        return escape(this).replace(/%/g, '\\'); 
    }; 

    String.charCodeToCnString = function(charCodes, regexp) { 
        return charCodes.replace(regexp, function($0, $1, $2) { 
            return String.fromCharCode( 
                parseInt($2, 16)/*把16进制的字符串转换成int型数字*/ 
            ); 
        }); 
    }; 
    String.asciiToCnString = function(asciiChars) {//ascii转换成汉字 
        return String.charCodeToCnString(asciiChars, /(\&#x)(\w{4})/gi); 
    }; 

    String.unicodeToCnString = function(unicodeChars) {//unicode转换成汉字,高效的.. 

        return unicodeChars + '';//虽然它已经是String类型,但再这样转换成String类型,居然直接变汉字了。 
        //unicodeChars.split('\\u')[0];split也可以变成汉字,可以用任意'非中文字符'来split,如'\\','safdasf'等等。 
        //unicodeChars.split('').join('');//也是可以的,这样每个字都成为数组的一个元素,与上一句一样 
        //return String.charCodeToCnString(unicodeChars, /(\&#x)(\w{4})/gi); 这个效率最差 
    }; 



    </script> 
    <body> 
    <script> 
    alert("冯瑶我爱你!".ulength()); 
    alert("冯瑶我爱你!".cnStringToAscii()); 
    alert("冯瑶我爱你!".cnStringToUnicode()); 
    </script> 
    </body> 
    </html> 

  • 相关阅读:
    js正则表达式验证【引用网址】
    Chart控件的使用实例
    C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解
    C#进阶系列——WebApi 接口参数不再困惑:传参详解
    C#进阶系列——WebApi 路由机制剖析:你准备好了吗?
    【UiPath 中文教程】02
    八幅漫画理解使用JSON Web Token设计单点登录系统
    JSON Web Token(缩写 JWT) 目前最流行的跨域认证解决方案
    webservice 教程
    IBM MQ 使用指南
  • 原文地址:https://www.cnblogs.com/zhuzhiyuan/p/2330852.html
Copyright © 2011-2022 走看看