Last active
November 21, 2023 02:30
-
-
Save muzi131313/46169bf8384eb589be8a9dc50ade0054 to your computer and use it in GitHub Desktop.
base64-to-string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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