Node.js 处理16进制 Unicode 中文字符串
Nodejs 中读取到像\u6210
以\u
的开头字符串,这不是乱码,这是16进制Unicode编码。它很好处理。
Unescape Unicode
我们可以使用进制转换的方法,将16进制的中文转成可阅读的utf-8
编码的中文。
const unescapeUnicode = (str) => {
return str.replace(/\\u[\dA-F]{4}/gi, (match) => {
return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
});
};
Deprecated unescape
unescape
是一个已经被废弃的方法,它的作用是将%u
开头的16进制Unicode编码转成可阅读的utf-8
编码的中文。
const unescapeUnicode = (str) => {
return unescape(str.replace(/\\u/g, '%u'));
}
使用JSON.parse()
自动转换
如果你的数据是JSON字符串,那么使用内置的JSON.parse()
方法,可以自动将16进制Unicode编码转成可阅读的utf-8
编码的中文。
const unescapeUnicodeJSON = (str) => {
return JSON.parse(str);
}