node.js - Node js 解析外来字符

标签 node.js character translate

我有一个 Node js 脚本,它从服务器获取一些数据并获取可读字符串。

我用来将十六进制转换为字符串的函数如下:

function hex2a(hexx) {
    var hex = hexx.toString();//force conversion
    var str = '';
    for (var i = 0; i < hex.length; i += 2)
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));

    return str;
}

这适用于大多数字符串,但当涉及到外文字母时,我无法让它工作。

例如:

以下内容: enter image description here

是我想要在console.log cmd窗口中显示的字符串。

十六进制如下(显然......):

D9 87 D9 86 DA AF 20 D8 B3 D9 88 D8 A7 D8 B1 5B

这就是在cmd中输出以下内容:

Ù?Ù?Ú¯ سÙ?ار

我怎样才能让它工作,以便它向我显示正确的输出,即图像中显示的内容?

最佳答案

这对我来说看起来像 UTF-8 see reference here

一种方法是使用 \u 转义每个字符,如下所示,console.log('\u00d9\u0087\u00D9');

在 Node 的 .12 版本中,有 this option

还有一些非常酷的模块可以为您执行此操作,请查看 the utf8 module

//from docs
// → '\xA9' 

utf8.decode('\xF0\x90\x80\x81');

关于node.js - Node js 解析外来字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29479644/

相关文章:

javascript - NodeJS 和 Passport 注册不工作 - 没有错误

Python 3.3 : printing special symbols like ♥ and ❦ when running through command line

java - 如何在使用 ANTLR (使用 java)解析文件后保存文件?

node.js - Nginx X-Accel-Redirect 不适用于 node.js

node.js - 通过 G Suite 电子邮件地址从服务器发送电子邮件

c - 如何在 C 语言中逐个字符地打印字符串?

html - 所有 html 实体字符映射列表

MySQL 查询到 MS SQL

php - Laravel 在翻译字符串中使用翻译器

node.js - 来自 Node.js 的 MongoDB 查询 (express-coffeescript-mongodb)