Unicode字符处理

最近做爬虫程序,偶尔会在返回的内容中看到一堆类似这样的东西天堂向左,深圳向右,一时间不知道怎么把它们转成中文。于是上网求救,发现解决方案后感觉so easy。其实很多东西不明白之前都很难,明白了就很简单,我是不是在说废话呢???

其实这串字符中的数字就是对应unicode字符的十进制表示方式,所以我们只要通过String.fromCodePoint进行简单的转化就可以得到想要的结果了。根据网友的提示,返回的内容还有可能是十六进制的,于是我自己写了个例子,备忘。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var code10, code16, zh;

code10 = '天堂向左,深圳向右';

zh = code10.replace(/&#(\d+);/g, function($, $1) {
return String.fromCodePoint($1)
});

console.log(zh);

code16 = zh.replace(/[^\u0000-\u00ff]/g, function($) {
return '&#x' + $.codePointAt(0).toString(16) + ';';
});

console.log(code16);

zh = code16.replace(/&#x(\w+);/g, function($, $1) {
return String.fromCodePoint(parseInt($1, 16))
});

console.log(zh);
文章目录
,