Python 的 urllib.quote() 和 urllib.unquote() 的等效 Javascript 函数 [英] Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote()

查看:21
本文介绍了Python 的 urllib.quote() 和 urllib.unquote() 的等效 Javascript 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Are there any equivalent Javascript functions for Python's urllib.quote() and urllib.unquote()?

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

The closest I've come across are escape(), encodeURI(), and encodeURIComponent() (and their corresponding un-encoding functions), but they don't encode/decode the same set of special characters as far as I can tell.

谢谢,
卡梅伦

推荐答案

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

OK, I think I'm going to go with a hybrid custom set of functions:

编码:使用encodeURIComponent(),然后把斜线放回去.
解码:解码找到的任何 %hex 值.

Encode: Use encodeURIComponent(), then put slashes back in.
Decode: Decode any %hex values found.

这是我最终使用的更完整的变体(它也能正确处理 Unicode):

Here's a more complete variant of what I ended up using (it handles Unicode properly, too):

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() 直接函数.

Note that if you don't need "safe" characters when encoding ('/' by default in Python), then you can just use the built-in encodeURIComponent() and decodeURIComponent() functions directly.

另外,如果字符串中有Unicode字符(即codepoint>=128的字符),那么为了保持与JavaScript的encodeURIComponent()的兼容性,Pythonquote_url()代码>必须是:

Also, if there are Unicode characters (i.e. characters with codepoint >= 128) in the string, then to maintain compatibility with JavaScript's encodeURIComponent(), the Python quote_url() would have to be:

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')

这篇关于Python 的 urllib.quote() 和 urllib.unquote() 的等效 Javascript 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆