我想拿一根绳子
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"
当前回答
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
其他回答
为什么不用呢?
$scope.get_location=function(url_str){
var parser = document.createElement('a');
parser.href =url_str;//"http://example.com:3000/pathname/?search=test#hash";
var info={
protocol:parser.protocol,
hostname:parser.hostname, // => "example.com"
port:parser.port, // => "3000"
pathname:parser.pathname, // => "/pathname/"
search:parser.search, // => "?search=test"
hash:parser.hash, // => "#hash"
host:parser.host, // => "example.com:3000"
}
return info;
}
alert( JSON.stringify( $scope.get_location("http://localhost:257/index.php/deploy/?asd=asd#asd"),null,4 ) );
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"
使用模块模式的简单而健壮的解决方案。这包括修复IE的路径名不总是有前导正斜杠(/)。
我已经创建了一个Gist和一个JSFiddle,它提供了一个更动态的解析器。我建议你检查一下并提供反馈。
var URLParser = (function (document) {
var PROPS = 'protocol hostname host pathname port search hash href'.split(' ');
var self = function (url) {
this.aEl = document.createElement('a');
this.parse(url);
};
self.prototype.parse = function (url) {
this.aEl.href = url;
if (this.aEl.host == "") {
this.aEl.href = this.aEl.href;
}
PROPS.forEach(function (prop) {
switch (prop) {
case 'hash':
this[prop] = this.aEl[prop].substr(1);
break;
default:
this[prop] = this.aEl[prop];
}
}, this);
if (this.pathname.indexOf('/') !== 0) {
this.pathname = '/' + this.pathname;
}
this.requestUri = this.pathname + this.search;
};
self.prototype.toObj = function () {
var obj = {};
PROPS.forEach(function (prop) {
obj[prop] = this[prop];
}, this);
obj.requestUri = this.requestUri;
return obj;
};
self.prototype.toString = function () {
return this.href;
};
return self;
})(document);
Demo
var URLParser = (function(document) { var PROPS = 'protocol hostname host pathname port search hash href'.split(' '); var self = function(url) { this.aEl = document.createElement('a'); this.parse(url); }; self.prototype.parse = function(url) { this.aEl.href = url; if (this.aEl.host == "") { this.aEl.href = this.aEl.href; } PROPS.forEach(function(prop) { switch (prop) { case 'hash': this[prop] = this.aEl[prop].substr(1); break; default: this[prop] = this.aEl[prop]; } }, this); if (this.pathname.indexOf('/') !== 0) { this.pathname = '/' + this.pathname; } this.requestUri = this.pathname + this.search; }; self.prototype.toObj = function() { var obj = {}; PROPS.forEach(function(prop) { obj[prop] = this[prop]; }, this); obj.requestUri = this.requestUri; return obj; }; self.prototype.toString = function() { return this.href; }; return self; })(document); /* Main */ var out = document.getElementById('out'); var urls = [ 'https://www.example.org:5887/foo/bar?a=1&b=2#section-1', 'ftp://www.files.com:22/folder?id=7' ]; var parser = new URLParser(); urls.forEach(function(url) { parser.parse(url); println(out, JSON.stringify(parser.toObj(), undefined, ' '), 0, '#0000A7'); }); /* Utility functions */ function print(el, text, bgColor, fgColor) { var span = document.createElement('span'); span.innerHTML = text; span.style['backgroundColor'] = bgColor || '#FFFFFF'; span.style['color'] = fgColor || '#000000'; el.appendChild(span); } function println(el, text, bgColor, fgColor) { print(el, text, bgColor, fgColor); el.appendChild(document.createElement('br')); } body { background: #444; } span { background-color: #fff; border: thin solid black; display: inline-block; } #out { display: block; font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif; font-size: 12px; white-space: pre; } <div id="out"></div>
输出
{
"protocol": "https:",
"hostname": "www.example.org",
"host": "www.example.org:5887",
"pathname": "/foo/bar",
"port": "5887",
"search": "?a=1&b=2",
"hash": "section-1",
"href": "https://www.example.org:5887/foo/bar?a=1&b=2#section-1",
"requestUri": "/foo/bar?a=1&b=2"
}
{
"protocol": "ftp:",
"hostname": "www.files.com",
"host": "www.files.com:22",
"pathname": "/folder",
"port": "22",
"search": "?id=7",
"hash": "",
"href": "ftp://www.files.com:22/folder?id=7",
"requestUri": "/folder?id=7"
}
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;
}