0

我注意到 Chrome 和 Firefox 存储document.location.hrefURL 编码,而 IE9 存储它未编码。

例如:

  • 铬/FF:http://domain.tld/some%20folder/
  • IE:http://domain.tld/some folder/

有什么约定吗?更重要的是,有没有一种可靠的方法可以在不检查供应商的情况下检查它是否是 URL 编码的?

我目前的解决方案是:

    // helpers
var reUriToPathname = /^.*:\/\/[^\/]*|[^\/]*$/g,
    uriToPathname = function (uri) {

        return uri.replace(reUriToPathname, '');
    },
    forceEncoding = function (href) {

        // collection of manual fixes..
        return href
                .replace(/\/+/g, '/')
                .replace(/ /g, '%20')
                .replace(/'/g, '%27')
                .replace(/\[/g, '%5B')
                .replace(/\]/g, '%5D')
                .replace(/\(/g, '%28')
                .replace(/\)/g, '%29')
                .replace(/\+/g, '%2B')
                .replace(/\=/g, '%3D');
    },

    // check once with a testpath
    hrefsAreDecoded = (function () {

        var testpathname = '/a b',
            a = doc.createElement('a');

        a.href = testpathname;
        return uriToPathname(a.href) === testpathname;
    }()),

    // safely return encoded href
    getEncodedHref = function (href) {

        var a = doc.createElement('a'),
            location;

        a.href = href;
        location = uriToPathname(a.href);

        if (hrefsAreDecoded) {
            location = encodeURIComponent(location).replace(/%2F/ig, '/');
        }

        return forceEncoding(location);
    };

使用getEncodedHref(document.location.href)似乎足够安全,但不是最好的解决方案。有什么建议可以更优雅地处理这个问题吗?

4

1 回答 1

0

怎么样:

encodeURIComponent("http://asdf.com?foo=bar&bla=asdfäöü");
"http%3A%2F%2Fasdf.com%3Ffoo%3Dbar%26bla%3Dasdf%C3%A4%C3%B6%C3%BC"

encodeURI("http://asdf.com?foo=bar&bla=asdfäöü");
"http://asdf.com?foo=bar&bla=asdf%C3%A4%C3%B6%C3%BC"
于 2012-10-22T18:42:08.847 回答