我想拿一根绳子
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"
当前回答
下面是一个使用regexp的简单函数,它模仿了a标记行为。
Pros
可预测的行为(无跨浏览器问题) 不需要DOM 它真的很短。
Cons
regexp有点难读
-
function getLocation(href) {
var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
return match && {
href: href,
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7]
}
}
-
getLocation("http://example.com/");
/*
{
"protocol": "http:",
"host": "example.com",
"hostname": "example.com",
"port": undefined,
"pathname": "/"
"search": "",
"hash": "",
}
*/
getLocation("http://example.com:3000/pathname/?search=test#hash");
/*
{
"protocol": "http:",
"host": "example.com:3000",
"hostname": "example.com",
"port": "3000",
"pathname": "/pathname/",
"search": "?search=test",
"hash": "#hash"
}
*/
编辑:
下面是正则表达式的分解
var reURLInformation = new RegExp([
'^(https?:)//', // protocol
'(([^:/?#]*)(?::([0-9]+))?)', // host (hostname and port)
'(/{0,1}[^?#]*)', // pathname
'(\\?[^#]*|)', // search
'(#.*|)$' // hash
].join(''));
var match = href.match(reURLInformation);
其他回答
当然,在>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://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;
}
为什么不用呢?
$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"