利用fromCharCode() 和escape对汉字编码解码

escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串。该方法不会对 ASCII 字母和数字进行编码,也不会对下面这些 ASCII 标点符号进行编码: * @ - _ + . / 。其他所有的字符都会被转义序列替换。

fromCharCode() 可接受一个指定的 Unicode 值,然后返回一个字符串。

所以Javascrip使用这两个函数结合就能实对汉字转实体码 unicode编码

<script type="text/javascript">
//http://www.bangnishouji.com/tools/chtounicode.html
function action(pChoice){ 
switch(pChoice){ 
case "CONVERT_FMT1": 
    $("#show2").val(ascii($("#source").val()));
    break; 
case "CONVERT_FMT2": 
    $("#show2").val(unicode($("#source").val())); 
    break; 
case "RECONVERT": 
    $("#show2").val(reconvert($("#source").val())); 
    break; 
} 
} 
function ascii(str){ 
return str.replace(/[^\u0000-\u00FF]/g,function($0){return escape($0).replace(/(%u)(\w{4})/gi,"\&#x$2;")}); 
} 
function unicode(str){ 
return str.replace(/[^\u0000-\u00FF]/g,function($0){return escape($0).replace(/(%u)(\w{4})/gi,"\\u$2")}); 
} 
function reconvert(str){ 
str = str.replace(/(\\u)(\w{4})/gi,function($0){ 
return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{4})/g,"$2")),16))); 
}); 
str = str.replace(/(&#x)(\w{4});/gi,function($0){ 
return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{4})(%3B)/g,"$2"),16)); 
}); 
return str; 
} 
</script>

演示地址:汉字转Unicode

 

转载于:https://www.cnblogs.com/bangnishouji/p/3469466.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值