Skip to content

Instantly share code, notes, and snippets.

@iflamed
Created August 14, 2023 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iflamed/d3f3e5eabcde951b0f066b6b289499b4 to your computer and use it in GitHub Desktop.
Save iflamed/d3f3e5eabcde951b0f066b6b289499b4 to your computer and use it in GitHub Desktop.
微信小程序 Uint8Array to String 支持utf8
TextEncoder:
var encoder = new TextEncoder()
encoder.encode("中文abc🍎");
//result : Uint8Array(9) [228, 184, 173, 230, 150, 135, 97, 98, 99, 240, 159, 141, 142]
//兼容写法1:
unescape(encodeURIComponent("中文abc🍎")).split("").map(val => val.charCodeAt());
//result : (9) [228, 184, 173, 230, 150, 135, 97, 98, 99, 240, 159, 141, 142]
//兼容写法2:
encodeURIComponent("中文abc🍎").split("").map(val => val.charCodeAt());
//result : (33) [37, 69, 52, 37, 66, 56, 37, 65, 68, 37, 69, 54, 37, 57, 54, 37, 56, 55, 97, 98, 99, 37, 70, 48, 37, 57, 70, 37, 56, 68, 37, 56, 69]
TextDecoder:
var decoder = new TextDecoder();
decoder.decode(Uint8Array.from([228, 184, 173, 230, 150, 135, 97, 98, 99, 240, 159, 141, 142]));
//result : 中文abc🍎
//兼容写法1:
decodeURIComponent(escape(String.fromCharCode(...[228, 184, 173, 230, 150, 135, 97, 98, 99, 240, 159, 141, 142])));
//result : 中文abc🍎
//兼容写法2:
decodeURIComponent(String.fromCharCode(...[37, 69, 52, 37, 66, 56, 37, 65, 68, 37, 69, 54, 37, 57, 54, 37, 56, 55, 97, 98, 99, 37, 70, 48, 37, 57, 70, 37, 56, 68, 37, 56, 69]));
//result : 中文abc🍎
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment