我想拿一根绳子

var a = "http://example.com/aa/bb/"

然后把它加工成一个物体

a.hostname == "example.com"

and

a.pathname == "/aa/bb"

当前回答

现代方式:

new URL("http://example.com/aa/bb/")

返回一个具有主机名和路径名等属性的对象。

第一个参数是相对或绝对URL;如果它是相对的,那么你需要指定第二个参数(基本URL)。例如,对于相对于当前页面的URL:

new URL("/aa/bb/", location)

除了浏览器,这个API在Node.js中也可以通过require('url'). url从v7开始使用。

其他回答

对于那些正在寻找在IE, Firefox和Chrome中工作的现代解决方案的人:

这些使用超链接元素的解决方案都不会在chrome中起同样的作用。如果你传递一个无效(或空白)的url给chrome,它总是会返回脚本被调用的主机。所以在IE中你会得到空白,而在Chrome中你会得到localhost(或其他什么)。

如果你试图看着推荐人,这是骗人的。你需要确保你返回的主机在原始url中,以处理这个问题:

    function getHostNameFromUrl(url) {
        // <summary>Parses the domain/host from a given url.</summary>
        var a = document.createElement("a");
        a.href = url;

        // Handle chrome which will default to domain where script is called from if invalid
        return url.indexOf(a.hostname) != -1 ? a.hostname : '';
    }

第一个答案的简单破解

var getLocation = function(href=window.location.href) {
    var l = document.createElement("a");
    l.href = href;
    return l;
};

即使没有参数,也可以使用它来计算当前的主机名 getLocation()。Hostname将给出当前主机名

当然,在>2016年,正确的答案是使用URL API 对于页面URL window.location And for <a href="…""> html lanchorelement API

也支持旧浏览器,使用polyfill:

<script crossorigin="anonymous" src="https://polyfill.io/v3/polyfill.min.js?features=URL"></script>

但作为另一种选择,它可以通过RegEx模式简单而准确地处理:

function URIinfo(s) { s=s.match(/^(([^/]*?:)\/*((?:([^:]+):([^@]+)@)?([^/:]{2,}|\[[\w:]+])(:\d*)?(?=\/|$))?)?((.*?\/)?(([^/]*?)(\.[^/.]+?)?))(\?.*?)?(#.*)?$/); return {origin:s[1],protocol:s[2],host:s[3],username:s[4],password:s[5],hostname:s[6],port:s[7],path:s[8],folders:s[9],file:s[10],filename:s[11],fileext:s[12],search:s[13],hash:s[14]}; } var sample='http://user:password@my.site.com:8080/onefolder/folder.name/file.min.js?query=http://my.site.com:8080/file.exe#hash-root:/file/1.txt'; console.log (URIinfo(sample)); /* { "origin": "http://user:password@my.site.com:8080", "protocol": "http:", "host": "user:password@my.site.com:8080", "username": "user", "password": "password", "hostname": "my.site.com", "port": ":8080", "path": "/onefolder/folder.name/file.min.js", "folders": "/onefolder/folder.name/", "file": "file.min.js", "filename": "file.min", "fileext": ".js", "search": "?query=http://my.site.com:8080/file.exe", "hash": "#hash-root:/file/1.txt" } */

使用正则表达式

任何形式的

绝对/相对路径 IPv4 / IPv6 网络协议/本地文件 查询/散列

返回所有URL选项,但不返回searchParams

(+)也将返回文件信息,如PHP pathInfo

freddiefujiwara的答案很好,但我也需要在ie中支持相对url。我想出了以下解决方案:

function getLocation(href) {
    var location = document.createElement("a");
    location.href = href;
    // IE doesn't populate all link properties when setting .href with a relative URL,
    // however .href will return an absolute URL which then can be used on itself
    // to populate these additional fields.
    if (location.host == "") {
      location.href = location.href;
    }
    return location;
};

现在使用它来获得所需的属性:

var a = getLocation('http://example.com/aa/bb/');
document.write(a.hostname);
document.write(a.pathname);

例子:

function getLocation(href) { var location = document.createElement("a"); location.href = href; // IE doesn't populate all link properties when setting .href with a relative URL, // however .href will return an absolute URL which then can be used on itself // to populate these additional fields. if (location.host == "") { location.href = location.href; } return location; }; var urlToParse = 'http://example.com/aa/bb/', a = getLocation(urlToParse); document.write('Absolute URL: ' + urlToParse); document.write('<br />'); document.write('Hostname: ' + a.hostname); document.write('<br />'); document.write('Pathname: ' + a.pathname);

别再白费力气了。使用https://github.com/medialize/URI.js/

var uri = new URI("http://example.org:80/foo/hello.html");
// get host
uri.host(); // returns string "example.org:80"
// set host
uri.host("example.org:80");