原生js支持的编码转换方法

### 直接上代码
关于js编码转化的原生方法

var encodedData = btoa('Hello, world'); // encode a string
var decodedData = atob(encodedData); // decode the string
function utoa(str) {
    return window.btoa(unescape(encodeURIComponent(str)));
}
// base64 encoded ascii to ucs-2 string
function atou(str) {
    return decodeURIComponent(escape(window.atob(str)));
}
// 使用:
utoa('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
atou('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"

utoa('I \u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
atou('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"

总结一下

  • btoa 将普通字符串转化为base64编码
  • atou base64编码转化为普通字符串
  • escape 可对字符串进行编码
  • unescape 可对字符串进行解码
  • encodeURIComponent(URIstring) 把字符串作为URI组件进行编码。
    • URIstring 必需。一个字符串,含有URI组件或其他要编码的文本。
  • decodeURIComponent 把字符串作为URI组件进行解码。
    • URIstring 必需。一个字符串,含有URI组件或其他要编码的文本。

注:关于URL和URI的区别可以看看这个

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值