JavaScript中与Python的urllib.parse.quote()和urllib.parse.unquote()等效的函数是什么?

46 投票
8 回答
36292 浏览
提问于 2025-04-15 12:01

有没有和Python的 urllib.parse.quote()urllib.parse.unquote() 功能相似的JavaScript函数呢?

我找到的最接近的函数是 encodeURI()encodeURIComponent() 还有 escape()(以及它们对应的解码函数),但据我所知,它们编码和解码的特殊字符集并不完全相同。

8 个回答

6

requests库在使用上更受欢迎,前提是你不介意多加一个依赖。

from requests.utils import quote
quote(str)
101
JavaScript               |  Python
----------------------------------- 
encodeURI(str)           |  urllib.parse.quote(str, safe='~@#$&()*!+=:;,?/\'');
-----------------------------------
encodeURIComponent(str)  |  urllib.parse.quote(str, safe='~()*!\'')

在Python 3.7及以上版本中,你可以把safe=中的~去掉。

6

好的,我决定使用一套混合的自定义函数:

编码:先用 encodeURIComponent(),然后再把斜杠加回来。
解码:解码任何找到的 %hex 值。

这是我最终使用的一个更完整的版本(它也能正确处理 Unicode):

function quoteUrl(url, safe) {
    if (typeof(safe) !== 'string') {
        safe = '/';    // Don't escape slashes by default
    }

    url = encodeURIComponent(url);

    // Unescape characters that were in the safe list
    toUnencode = [  ];
    for (var i = safe.length - 1; i >= 0; --i) {
        var encoded = encodeURIComponent(safe[i]);
        if (encoded !== safe.charAt(i)) {    // Ignore safe char if it wasn't escaped
            toUnencode.push(encoded);
        }
    }

    url = url.replace(new RegExp(toUnencode.join('|'), 'ig'), decodeURIComponent);

    return url;
}


var unquoteUrl = decodeURIComponent;    // Make alias to have symmetric function names

注意,如果你在编码时不需要“安全”的字符(在 Python 中默认是 '/'),那么你可以直接使用内置的 encodeURIComponent()decodeURIComponent() 函数。

另外,如果字符串中有 Unicode 字符(也就是字符编码大于等于 128 的字符),为了和 JavaScript 的 encodeURIComponent() 保持兼容,Python 的 quote_url() 需要这样写:

def quote_url(url, safe):
    """URL-encodes a string (either str (i.e. ASCII) or unicode);
    uses de-facto UTF-8 encoding to handle Unicode codepoints in given string.
    """
    return urllib.quote(unicode(url).encode('utf-8'), safe)

unquote_url() 则是:

def unquote_url(url):
    """Decodes a URL that was encoded using quote_url.
    Returns a unicode instance.
    """
    return urllib.unquote(url).decode('utf-8')

撰写回答