Skip to content

Instantly share code, notes, and snippets.

@muzi131313
Last active November 21, 2023 02:30
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 muzi131313/46169bf8384eb589be8a9dc50ade0054 to your computer and use it in GitHub Desktop.
Save muzi131313/46169bf8384eb589be8a9dc50ade0054 to your computer and use it in GitHub Desktop.
base64-to-string
// from: https://mp.weixin.qq.com/s/qxi_28ozTZqjLeJNlpR6rA
// 来自https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem.
function base64ToBytes(base64) {
const binString = atob(base64);
return Uint8Array.from(binString, (m) => m.codePointAt(0));
}
// 来自https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem.
function bytesToBase64(bytes) {
const binString = String.fromCodePoint(...bytes);
return btoa(binString);
}
// 由于旧版浏览器不支持isWellFormed(),可以快速创建polyfill。
// encodeURIComponent()对于单独代理会抛出错误,这本质上是相同的。
function isWellFormed(str) {
if (typeof(str.isWellFormed)!="undefined") {
// Use the newer isWellFormed() feature.
return str.isWellFormed();
} else {
// Use the older encodeURIComponent().
try {
encodeURIComponent(str);
return true;
} catch (error) {
return false;
}
}
}
const validUTF16String = 'hello⛳❤️🧀';
const partiallyInvalidUTF16String = 'hello⛳❤️🧀\uDE75';
if (isWellFormed(validUTF16String)) {
// 这将会成功。它将打印:
// 编码后的字符串: [aGVsbG/im7PinaTvuI/wn6eA]
const validUTF16StringEncoded = bytesToBase64(new TextEncoder().encode(validUTF16String));
console.log(`Encoded string: [${validUTF16StringEncoded}]`);
// 这将会成功。它将打印:
// 解码后的字符串: [hello⛳❤️🧀]
const validUTF16StringDecoded = new TextDecoder().decode(base64ToBytes(validUTF16StringEncoded));
console.log(`Decoded string: [${validUTF16StringDecoded}]`);
} else {
// 忽略
}
if (isWellFormed(partiallyInvalidUTF16String)) {
// 忽略
} else {
// 这不是一个格式良好的字符串,因此我们要处理这种情况。
console.log(`Cannot process a string with lone surrogates: [${partiallyInvalidUTF16String}]`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment