Node.js将字符串转换为UTF-8 [英] Nodejs convert string into UTF-8
问题描述
从我的数据库中获取以下字符串:
From my DB im getting the following string:
Johan Öbert
它应该说的是:
Johan Öbert
我试图像这样将其转换为utf-8:
I've tried to convert it into utf-8 like so:
nameString.toString("utf8");
但还是同样的问题.
有什么想法吗?
推荐答案
使用npm中的 utf8 模块编码/解码字符串.
Use the utf8 module from npm to encode/decode the string.
安装:
npm install utf8
在浏览器中:
<script src="utf8.js"></script>
在Node.js中:
const utf8 = require('utf8');
API:
编码:
utf8.encode(string)
将任何给定的JavaScript字符串(字符串)编码为UTF-8,并返回该字符串的UTF-8编码版本.如果输入字符串包含非标量值(即孤立代理),则会引发错误. (如果还需要编码非标量值,请改用WTF-8.)
Encodes any given JavaScript string (string) as UTF-8, and returns the UTF-8-encoded version of the string. It throws an error if the input string contains a non-scalar value, i.e. a lone surrogate. (If you need to be able to encode non-scalar values as well, use WTF-8 instead.)
// U+00A9 COPYRIGHT SIGN; see http://codepoints.net/U+00A9
utf8.encode('\xA9');
// → '\xC2\xA9'
// U+10001 LINEAR B SYLLABLE B038 E; see http://codepoints.net/U+10001
utf8.encode('\uD800\uDC01');
// → '\xF0\x90\x80\x81'
解码:
utf8.decode(byteString)
将任何给定的UTF-8编码字符串(byteString)解码为UTF-8,并返回该字符串的UTF-8解码版本.当检测到格式错误的UTF-8时,它将引发错误. (如果还需要解码编码的非标量值,请改用WTF-8.)
Decodes any given UTF-8-encoded string (byteString) as UTF-8, and returns the UTF-8-decoded version of the string. It throws an error when malformed UTF-8 is detected. (If you need to be able to decode encoded non-scalar values as well, use WTF-8 instead.)
utf8.decode('\xC2\xA9');
// → '\xA9'
utf8.decode('\xF0\x90\x80\x81');
// → '\uD800\uDC01'
// → U+10001 LINEAR B SYLLABLE B038 E
这篇关于Node.js将字符串转换为UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!