求一段JavaScript代码的解释:有关URL编码

在js中,可以用window.btoa(str)/window.atob(str)对字符串进行base64编解码,但是传入的字符串不支持非ASCII。所以有人写了对应Base64编解码的函数:

function b64Encode( str ) {
    return window.btoa(unescape(encodeURIComponent( str )));
}

function b64Decode( str ) {
    return decodeURIComponent(escape(window.atob( str )));
}

问题是:对于b64Encode函数为什么先要用encodeURIComponent,再用unescape?
先用escape再用decodeURIComponent不行吗?为什么是这个顺序。


另外还有个问题,escape函数和encodeURIComponent或encodeURI有什么重要的不同吗,为什么要废除escape函数。文档上说的不清不楚的,求解答。

阅读 5.2k
2 个回答

首先推荐阅读关于URL编码,它介绍了关于这四个编码函数的主要区别。

MDN上有相应的解释,也已经提供了具体的解决方案,所以顺序是可以颠倒的。

function utf8_to_b64( str ) {
    return window.btoa(encodeURIComponent( escape( str )));
}

function b64_to_utf8( str ) {
    return unescape(decodeURIComponent(window.atob( str )));
}

encodeURIComponentECMAScript上定义如下:

The encodeURIComponent function computes a new version of a URI in which each instance of certain characters is replaced by one, two or three escape sequences representing the UTF-8 encoding of the character.

由此可以看出encodeURIComponent是用UTF-8编码的。

escape是不能直接用于URL编码,它的真正作用是返回一个字符的Unicode编码值。

新手上路,请多包涵

escape它不会对 ASCII 字母和数字进行编码,也不会对下面这些 ASCII 标点符号进行编码: - _ . ! ~ ' ( )
encodeURI是utf-8的编码,但是不能解析特殊的字符,列如 @ $
encodeURIComponent是utf-8的编码,可以解析特殊的字符 @ $

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题