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

求一段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函数。文档上说的不清不楚的,求解答。


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

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

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

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

encodeURIComponent在ECMAScript上定义如下:

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编码值。

【热门文章】
【热门文章】