[英]how to convert a string containing utf8 hex codes to a javascript string
I have a string that contains hexadecimal string (content of a utf8 string )我有一个包含十六进制字符串的字符串(utf8 字符串的内容)
"666f6f6c 6973686e 6573732c 20697420 77617320 74686520 65706f63 68206f66 2062656c 6965662c 20697420 77617320 74686520 65706f63 68206f66 20696e63 72656475 6c697479 2c206974 20776173 20746865 20736561 736f6e20 6f66204c 69676874 2c206974 20776173 20746865 2073656"
I need to convert it back to a javascript string.我需要将它转换回 javascript 字符串。 how to do it?
怎么做?
var s = "666f6f6c 6973686e 6573732c 20697420 77617320 74686520 65706f63 68206f66 2062656c 6965662c 20697420 77617320 74686520 65706f63 68206f66 20696e63 72656475 6c697479 2c206974 20776173 20746865 20736561 736f6e20 6f66204c 69676874 2c206974 20776173 20746865 2073656";
var r = decodeURIComponent(s.replace(/\s+/g, '').replace(/[0-9a-f]{2}/g, '%$&'));
This solution actually handles UTF-8.该解决方案实际上处理 UTF-8。
The idea is to put a %
in front of every pair of hex digits (thus creating a URL encoded string), then letting decodeURIComponent
handle the details (in particular, it will correctly decode multi-byte UTF-8 characters).这个想法是在每对十六进制数字前放置一个
%
(从而创建一个 URL 编码字符串),然后让decodeURIComponent
处理细节(特别是,它将正确解码多字节 UTF-8 字符)。
To properly handle UTF8 you may want to try this approach:要正确处理 UTF8,您可能想尝试这种方法:
function utf8ToHex(str) {
return Array.from(str).map(c =>
c.charCodeAt(0) < 128 ? c.charCodeAt(0).toString(16) :
encodeURIComponent(c).replace(/\%/g,'').toLowerCase()
).join('');
},
function hexToUtf8: function(hex) {
return decodeURIComponent('%' + hex.match(/.{1,2}/g).join('%'));
}
Demo: https://jsfiddle.net/lyquix/k2tjbrvq/演示: https ://jsfiddle.net/lyquix/k2tjbrvq/
Node only solution.仅节点解决方案。 There's the
Buffer
class that can convert between data (eg utf bytes and utf8 strings.有一个
Buffer
类可以在数据之间进行转换(例如 utf 字节和 utf8 字符串。
Buffer.from(0x66, 0x6f, 0x6f, 0x6c).toString(); // 'fool'
So for your space-deliminated string format of bytes, you would:因此,对于以空格分隔的字节字符串格式,您将:
let s = '666f6f6c 6973686e 6573732c';
// [102, 111, 111, 108, 105, 115, 104, 110, 101, 115, 115, 44]
let bytes = [...s.matchAll(/[^ ]{1,2}/g)].map(a => parseInt('0x' + a[0]));
Buffer.from(bytes).toString(); // 'foolishness,'
Use this:用这个:
function HexToString(s) {
var escaped = "";
var hex = "";
if(s.length%4 > 0) {
for (i = 0; i < (4 - (s.length % 4)); i++) {
hex += "0";
}
}
hex += s;
for (var i = 0; i < hex.length; i += 4) {
escaped += "%u" + hex.charAt(i) + hex.charAt(i + 1) + hex.charAt(i + 2) + hex.charAt(i + 3);
}
return unescape(escaped).split(unescape("%00")).join("");
}
It's works for me.这对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.