我想拿一根绳子
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"
当前回答
在acdcjunior解决方案上扩展了“searchParam”功能 模仿URL对象,增加了“searchParam”来解析查询字符串 适用于IE 6、7、8、9、10、11
用法- (JSFiddle Link)
// USAGE:
var myUrl = new ParsedUrl("http://www.example.com/path?var1=123&var2=abc#fragment");
console.log(myUrl);
console.log(myUrl.searchParam('var1'));
console.log(myUrl.searchParam('var2'));
输出- (JSFiddle链接)
{
hash: "#fragment",
host: "www.example.com:8080",
hostname: "www.example.com",
href: "http://www.example.com:8080/path?var1=123&var2=abc#fragment",
pathname: "/path",
port: "80",
protocol: "http:",
search: "?var1=123&var2=abc"
}
"123"
"abc"
CODE - (JSFiddle Link)
function ParsedUrl(url) {
var parser = document.createElement("a");
parser.href = url;
// IE 8 and 9 dont load the attributes "protocol" and "host" in case the source URL
// is just a pathname, that is, "/example" and not "http://www.example.com/example".
parser.href = parser.href;
// IE 7 and 6 wont load "protocol" and "host" even with the above workaround,
// so we take the protocol/host from window.location and place them manually
if (parser.host === "") {
var newProtocolAndHost = window.location.protocol + "//" + window.location.host;
if (url.charAt(1) === "/") {
parser.href = newProtocolAndHost + url;
} else {
// the regex gets everything up to the last "/"
// /path/takesEverythingUpToAndIncludingTheLastForwardSlash/thisIsIgnored
// "/" is inserted before because IE takes it of from pathname
var currentFolder = ("/"+parser.pathname).match(/.*\//)[0];
parser.href = newProtocolAndHost + currentFolder + url;
}
}
// copies all the properties to this object
var properties = ['host', 'hostname', 'hash', 'href', 'port', 'protocol', 'search'];
for (var i = 0, n = properties.length; i < n; i++) {
this[properties[i]] = parser[properties[i]];
}
// pathname is special because IE takes the "/" of the starting of pathname
this.pathname = (parser.pathname.charAt(0) !== "/" ? "/" : "") + parser.pathname;
//search Params
this.searchParam = function(variable) {
var query = (this.search.indexOf('?') === 0) ? this.search.substr(1) : this.search;
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
return '';
};
}
其他回答
第一个答案的简单破解
var getLocation = function(href=window.location.href) {
var l = document.createElement("a");
l.href = href;
return l;
};
即使没有参数,也可以使用它来计算当前的主机名 getLocation()。Hostname将给出当前主机名
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://gist.github.com/1847816复制的一个版本,但经过重写,以便于阅读和调试。将锚数据的值复制到另一个名为“result”的变量的目的是因为锚数据相当长,因此将有限数量的值复制到结果将有助于简化结果。
/**
* See: https://gist.github.com/1847816
* Parse a URI, returning an object similar to Location
* Usage: var uri = parseUri("hello?search#hash")
*/
function parseUri(url) {
var result = {};
var anchor = document.createElement('a');
anchor.href = url;
var keys = 'protocol hostname host pathname port search hash href'.split(' ');
for (var keyIndex in keys) {
var currentKey = keys[keyIndex];
result[currentKey] = anchor[currentKey];
}
result.toString = function() { return anchor.href; };
result.requestUri = result.pathname + result.search;
return result;
}
在acdcjunior解决方案上扩展了“searchParam”功能 模仿URL对象,增加了“searchParam”来解析查询字符串 适用于IE 6、7、8、9、10、11
用法- (JSFiddle Link)
// USAGE:
var myUrl = new ParsedUrl("http://www.example.com/path?var1=123&var2=abc#fragment");
console.log(myUrl);
console.log(myUrl.searchParam('var1'));
console.log(myUrl.searchParam('var2'));
输出- (JSFiddle链接)
{
hash: "#fragment",
host: "www.example.com:8080",
hostname: "www.example.com",
href: "http://www.example.com:8080/path?var1=123&var2=abc#fragment",
pathname: "/path",
port: "80",
protocol: "http:",
search: "?var1=123&var2=abc"
}
"123"
"abc"
CODE - (JSFiddle Link)
function ParsedUrl(url) {
var parser = document.createElement("a");
parser.href = url;
// IE 8 and 9 dont load the attributes "protocol" and "host" in case the source URL
// is just a pathname, that is, "/example" and not "http://www.example.com/example".
parser.href = parser.href;
// IE 7 and 6 wont load "protocol" and "host" even with the above workaround,
// so we take the protocol/host from window.location and place them manually
if (parser.host === "") {
var newProtocolAndHost = window.location.protocol + "//" + window.location.host;
if (url.charAt(1) === "/") {
parser.href = newProtocolAndHost + url;
} else {
// the regex gets everything up to the last "/"
// /path/takesEverythingUpToAndIncludingTheLastForwardSlash/thisIsIgnored
// "/" is inserted before because IE takes it of from pathname
var currentFolder = ("/"+parser.pathname).match(/.*\//)[0];
parser.href = newProtocolAndHost + currentFolder + url;
}
}
// copies all the properties to this object
var properties = ['host', 'hostname', 'hash', 'href', 'port', 'protocol', 'search'];
for (var i = 0, n = properties.length; i < n; i++) {
this[properties[i]] = parser[properties[i]];
}
// pathname is special because IE takes the "/" of the starting of pathname
this.pathname = (parser.pathname.charAt(0) !== "/" ? "/" : "") + parser.pathname;
//search Params
this.searchParam = function(variable) {
var query = (this.search.indexOf('?') === 0) ? this.search.substr(1) : this.search;
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
return '';
};
}
今天我遇到了这个问题,我发现: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: "" }
希望我的第一篇文章能帮助到你!