代码之家  ›  专栏  ›  技术社区  ›  Cameron

python的urllib.quote()和urllib.unquote()的等效javascript函数

  •  31
  • Cameron  · 技术社区  · 17 年前

    有没有与python相同的javascript函数 urllib.quote() urllib.unquote() ?

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

    谢谢,
    卡梅伦

    5 回复  |  直到 8 年前
        1
  •  65
  •   mjhm    15 年前

    备案:

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

    好的,我想我将使用一组混合自定义函数:

    编码:使用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的兼容性 编码成分() 蟒蛇 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')
    
        3
  •  3
  •   Milimetric    8 年前

    这个 requests 如果你不介意额外的依赖,图书馆会更受欢迎。

    from requests.utils import quote
    quote(str)
    
        4
  •  1
  •   jiggy    17 年前

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

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

    它将用其对应的%hex表示形式替换序数255以上的任何字符。

        5
  •  1
  •   Luke Stanley    16 年前

    蟒蛇: urllib.quote

    Javascript: unescape

    我没有做过广泛的测试,但为了我的目的,它大部分时间都是有效的。我想你有一些特定的角色不起作用。也许如果我用一些亚洲文字或其他东西,它会被破坏:)

    这是我在谷歌上搜索的时候发现的,所以我把它放在所有其他人身上,如果不是专门针对原始问题的话。