JavaScript简介

JS中UTF-8与汉字互转

  关于在 JS 中UTF-8与汉字互转问题,搜到了很多方法,但就是这个方法最6。

利用正则匹配,代码少、效率较高。

函数定义

1
2
3
4
5
6
7
8
9
10
11
12
//UTF字符转换
let UTFTranslate = {
Change : function(pValue) {
return pValue.replace(/[^\u0000-\u00FF]/g, function($0) {
return escape($0).replace(/(%u)(\w{4})/gi, "&#x$2;")
});
},
ReChange : function(pValue) {
return unescape(pValue.replace(/&#x/g, '%u').replace(/\\u/g, '%u')
.replace(/;/g, ''));
}
};

使用

1
2
UTFTranslate.ReChange('中文sdfdf'); //"中文sdfdf"
UTFTranslate.Change('中文sdfsf'); // "中文sdfsf"

引用自这篇文章: JS中UTF编码与中文的互转


评论