封装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> 

posted @ 2012-01-29 10:04  web开发  阅读(2968)  评论(0编辑  收藏  举报