Python的urllib.quote()和urllib.unquote()的等效Javascript函数

时间:2009-06-03 17:51:28

标签: javascript python url encoding

Python的urllib.quote()urllib.unquote()是否有任何等效的Javascript函数?

我遇到的最接近的是escape()encodeURI()encodeURIComponent()(及其相应的非编码函数),但它们不对同一组进行编码/解码据我所知,特殊字符。

谢谢,
卡梅伦

5 个答案:

答案 0 :(得分:66)

记录:

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

答案 1 :(得分:6)

好的,我想我会选择一套混合的自定义函数:

编码:使用encodeURIComponent(),然后将斜杠放回。
解码:解码找到的任何%十六进制值。

这是我最终使用的更完整的变体(它也正确处理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')

答案 2 :(得分:3)

如果您不介意额外的依赖性,requests库会更受欢迎

from requests.utils import quote
quote(str)

答案 3 :(得分:1)

试试正则表达式。像这样:

mystring.replace(/[\xFF-\xFFFF]/g, "%" + "$&".charCodeAt(0));

这将用相应的%HEX表示替换序号255以上的任何字符。

答案 4 :(得分:1)

Python:urllib.quote

使用Javascript:unescape

我没有进行过广泛的测试,但出于我的目的,它大部分时间都有效。我想你有一些不起作用的特定字符。也许如果我使用一些亚洲文字或其他东西会破坏:)

当我用谷歌搜索时,这就出现了,所以我把它放在所有其他人身上,如果不是专门用于原始问题的话。