---
title: "Node.js 处理16进制 Unicode 中文字符串"
date: 2022-11-01T16:12:07.000Z
author: Z.SHINCHVEN
tags: [Node.js, Unicode, 中文, encoding]
canonical: https://atlassc.net/2022/11/02/nodejs-handle-unicode-chinese
---
Nodejs 中读取到像`\u6210`以`\u`的开头字符串，这不是乱码，这是16进制[Unicode](https://zh.wikipedia.org/wiki/Unicode)编码。它很好处理。

## Unescape Unicode

我们可以使用进制转换的方法，将16进制的中文转成可阅读的`utf-8`编码的中文。

```js
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`编码的中文。

```js
const unescapeUnicode = (str) => {
  return unescape(str.replace(/\\u/g, '%u'));
}
```

## 使用`JSON.parse()`自动转换

如果你的数据是JSON字符串，那么使用内置的`JSON.parse()`方法，可以自动将16进制Unicode编码转成可阅读的`utf-8`编码的中文。

```js
const unescapeUnicodeJSON = (str) => {
  return JSON.parse(str);
}
```
