我想拿一根绳子

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

然后把它加工成一个物体

a.hostname == "example.com"

and

a.pathname == "/aa/bb"

当前回答

第一个答案的简单破解

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

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

其他回答

怎么样?

'https://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript'.split('//').pop() .split('/')[0]

结果:

“stackoverflow.com”

别再白费力气了。使用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");

js-uri(在谷歌Code上可用)接受字符串URL并从中解析URI对象:

var some_uri = new URI("http://www.example.com/foo/bar");

alert(some_uri.authority); // www.example.com
alert(some_uri);           // http://www.example.com/foo/bar

var blah      = new URI("blah");
var blah_full = blah.resolve(some_uri);
alert(blah_full);         // http://www.example.com/foo/blah

今天我遇到了这个问题,我发现:URL - MDN Web api

var url = new URL("http://test.example.com/dir/subdir/file.html#hash");

这返回:

{ hash:"#hash", host:"test.example.com", hostname:"test.example.com", href:"http://test.example.com/dir/subdir/file.html#hash", origin:"http://test.example.com", password:"", pathname:"/dir/subdir/file.html", port:"", protocol:"http:", search: "", username: "" }

希望我的第一篇文章能帮助到你!

当然,在>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