素材牛VIP会员
求一段JavaScript代码的解释:有关URL编码
 闪***星  分类:Node.js  人气:686  回帖:2  发布于6年前 收藏

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

讨论这个帖子(2)垃圾回帖将一律封号处理……

Lv7 码师
ph***16 JAVA开发工程师 6年前#1

首先推荐阅读关于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编码值。

Lv5 码农
阿***d 交互设计师 6年前#2

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

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取