我想拿一根绳子
var a = "http://example.com/aa/bb/"
然后把它加工成一个物体
a.hostname == "example.com"
and
a.pathname == "/aa/bb"
我想拿一根绳子
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://gist.github.com/jlong/2428561
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.host; // => "example.com:3000"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.hash; // => "#hash"
parser.search; // => "?search=test"
parser.origin; // => "http://example.com:3000"
var getLocation = function(href) {
var l = document.createElement("a");
l.href = href;
return l;
};
var l = getLocation("http://example.com/path");
console.debug(l.hostname)
>> "example.com"
console.debug(l.pathname)
>> "/path"
别再白费力气了。使用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");
你也可以使用来自Locutus项目(前php.js)的parse_url()函数。
代码:
parse_url('http://username:password@hostname/path?arg=value#anchor');
结果:
{
scheme: 'http',
host: 'hostname',
user: 'username',
pass: 'password',
path: '/path',
query: 'arg=value',
fragment: 'anchor'
}
function parseUrl(url) {
var m = url.match(/^((?:([^:\/?#]+:)(?:\/\/))?((?:([^\/?#:]*):([^\/?#:]*)@)?([^\/?#:]*)(?::([^\/?#:]*))?))?([^?#]*)(\?[^#]*)?(#.*)?$/),
r = {
hash: m[10] || "", // #asd
host: m[3] || "", // localhost:257
hostname: m[6] || "", // localhost
href: m[0] || "", // http://username:password@localhost:257/deploy/?asd=asd#asd
origin: m[1] || "", // http://username:password@localhost:257
pathname: m[8] || (m[1] ? "/" : ""), // /deploy/
port: m[7] || "", // 257
protocol: m[2] || "", // http:
search: m[9] || "", // ?asd=asd
username: m[4] || "", // username
password: m[5] || "" // password
};
if (r.protocol.length == 2) {
r.protocol = "file:///" + r.protocol.toUpperCase();
r.origin = r.protocol + "//" + r.host;
}
r.href = r.origin + r.pathname + r.search + r.hash;
return r;
};
parseUrl("http://username:password@localhost:257/deploy/?asd=asd#asd");
它既适用于绝对url,也适用于相对url