sad*_*nsh 7 javascript base64 encoding
我一直在尝试将 twitter 嵌入代码编码到 base64 中,该代码可能包含也可能不包含一个或多个表情符号。因此,当字符串中有表情符号时,我会收到此错误:
Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
有什么我可以做的,当我在我的字符串上运行 btoa() 时,它会编码整个字符串,包括表情符号,当我在 php 中使用 base64_decode 解码时,表情符号再次出现?
提前致谢!
小智 11
您可以通过先对其进行转义然后对其调用 EncodeUriComponent 来对其进行编码。
这看起来像这样:
btoa(unescape(encodeURIComponent('')));Run Code Online (Sandbox Code Playgroud)
上面的表情符号将返回“8J+Ygg==”
要解码它,你会这样做
decodeURIComponent(escape(window.atob('8J+Ygg==')));Run Code Online (Sandbox Code Playgroud)
您可以创建两个函数,使这更容易一些:
//Encode
function utoa(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
//Decode
function atou(str) {
return decodeURIComponent(escape(window.atob(str)));
}Run Code Online (Sandbox Code Playgroud)
来源:https : //developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa
| 归档时间: |
|
| 查看次数: |
4918 次 |
| 最近记录: |