Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/457.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中将URL解析为主机名和路径?_Javascript_Url - Fatal编程技术网

如何在javascript中将URL解析为主机名和路径?

如何在javascript中将URL解析为主机名和路径?,javascript,url,Javascript,Url,我想要一根绳子 var a = "http://example.com/aa/bb/" 把它加工成一个物体 a.hostname == "example.com" 及 (可在谷歌代码中找到)获取字符串URL并从中解析URI对象: var some_uri = new URI("http://www.example.com/foo/bar"); alert(some_uri.authority); // www.example.com alert(some_uri); /

我想要一根绳子

var a = "http://example.com/aa/bb/"
把它加工成一个物体

a.hostname == "example.com"

(可在谷歌代码中找到)获取字符串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

这是我从中复制的一个版本,但经过重写,因此更易于阅读和调试。将锚定数据的值复制到另一个名为“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;

}

freddiefujiwara的回答很好,但我还需要在InternetExplorer中支持相对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);
例如:

函数getLocation(href){ 变量位置=document.createElement(“a”); location.href=href; //IE在使用相对URL设置.href时不会填充所有链接属性, //但是,href将返回一个绝对URL,然后可以在其自身上使用该URL //以填充这些附加字段。 如果(location.host==“”){ location.href=location.href; } 返回位置; }; var urlToParse=http://example.com/aa/bb/', a=获取位置(urlToParse); document.write('absoluteurl:'+urlToParse); 文件。写入(“
”); document.write('Hostname:'+a.Hostname); 文件。写入(“
”); document.write('Pathname:'+a.Pathname)您还可以使用project中的函数(以前的php.js)

代码:

结果:

{
  scheme: 'http',
  host: 'hostname',
  user: 'username',
  pass: 'password',
  path: '/path',
  query: 'arg=value',
  fragment: 'anchor'
}
{
    hash: "#fragment"
    host: "www.example.com:8080"
    hostname: "www.example.com"
    href: "http://www.example.com:8080/path?query=123#fragment"
    pathname: "/path"
    port: "8080"
    protocol: "http:"
    search: "?query=123"
}
可在此处找到:


AngularJS的方式-在这里拉小提琴:


使用AngularJS解析URL
使用AngularJS解析URL
网址:
  • href={{parser.href}
  • 协议={{parser.protocol}}
  • host={{parser.host}
  • 主机名={{parser.hostname}
  • 端口={{parser.port}
  • 路径名={{parser.pathname}
  • hash={{parser.hash}
  • search={{parser.search}
函数AppCtrl($scope){ $scope.$watch('url',function(){ $scope.parser.href=$scope.url; }); $scope.init=函数(){ $scope.parser=document.createElement('a'); $scope.url=window.location; } }
对于那些寻求在IE、Firefox和Chrome中工作的现代解决方案的人:

这些使用超链接元素的解决方案在chrome中的效果都不一样。如果将无效(或空白)url传递给chrome,它将始终返回调用脚本的主机。因此,在IE中,您将获得空白,而在Chrome中,您将获得localhost(或其他)

如果你试图看推荐人,这是欺骗。您需要确保返回的主机位于原始url中,以处理此问题:

    function getHostNameFromUrl(url) {
        // <summary>Parses the domain/host from a given url.</summary>
        var a = document.createElement("a");
        a.href = url;

        // Handle chrome which will default to domain where script is called from if invalid
        return url.indexOf(a.hostname) != -1 ? a.hostname : '';
    }
函数getHostNameFromUrl(url){ //从给定url解析域/主机。 var a=document.createElement(“a”); a、 href=url; //处理chrome,如果无效,它将默认为从中调用脚本的域 返回url.indexOf(a.hostname)!=-1?a.hostname:“”; }
这里有一个简单的函数,它使用一个regexp来模拟
标记行为

专业人士

  • 可预测的行为(无跨浏览器问题)
  • 不需要DOM
  • 它真的很短
缺点

  • regexp有点难读
-

-

编辑:

下面是正则表达式的分解

var reURLInformation = new RegExp([
    '^(https?:)//', // protocol
    '(([^:/?#]*)(?::([0-9]+))?)', // host (hostname and port)
    '(/{0,1}[^?#]*)', // pathname
    '(\\?[^#]*|)', // search
    '(#.*|)$' // hash
].join(''));
var match = href.match(reURLInformation);
现代方式:

new URL("http://example.com/aa/bb/")
返回具有属性
主机名
路径名
的对象,以及

第一个参数是相对或绝对URL;如果是相对的,则需要指定第二个参数(基本URL)。例如,对于相对于当前页面的URL:

new URL("/aa/bb/", location)

除了浏览器之外,从v7开始,通过
require('url')。url

使用模块模式的简单而健壮的解决方案。这包括对IE的修复,其中
路径名
并不总是有前导正斜杠(
/

我已经创建了一个提供更动态解析器的。我建议你检查一下并提供反馈

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);
演示
var URLParser=(函数(文档){
var PROPS='protocol hostname主机路径名端口搜索哈希href'.split('');
var self=函数(url){
this.aEl=document.createElement('a');
解析(url);
};
self.prototype.parse=函数(url){
this.aEl.href=url;
如果(this.aEl.host==“”){
this.aEl.href=this.aEl.href;
}
道具。forEach(功能(道具){
开关(道具){
案例“哈希”:
this[prop]=this.aEl[prop].substr(1);
打破
违约:
this[prop]=this.aEl[prop];
}
},这个);
if(this.pathname.indexOf('/')!==0){
this.pathname='/'+this.pathname;
}
this.requestUri=this.pathname+this.search;
};
self.prototype.toObj=函数(){
var obj={};
道具。forEach(功能(道具){
obj[prop]=此[prop];
},这个);
obj.requestUri=this.requestUri;
返回obj;
};
self.prototype.toString=函数(){
返回此文件。href;
};
回归自我;
})(文件);
/*主要*/
var out=document.getElementById('out');
变量URL=[
'https://www.example.org:5887/foo/bar?a=1&b=2#section-1',
'ftp://www.files.com:22/folder?id=7'
];
var parser=新的URLParser();
forEach(函数(url){
parser.parse(url);
println(out,JSON.stringify(parser.toObj(),undefined',),0',#0000A7');
});
/*效用函数*/
功能打印(el、文本、bgColor、fgColor){
var span=document.createElement('span');
span.innerHTML=文本;
span.style['backgroundColor']=bgColor | | |'#FFFFFF';
span.style['color']=fgColor | |'#000000';
el.appendChild(span);
}
函数println(el、text、bgColor、fgColor){
打印(el、文本、bgColor、fgColor);
el.附录儿童(文件)
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);
new URL("http://example.com/aa/bb/")
new URL("/aa/bb/", location)
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);
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");
var loc = window.location;  // => "http://example.com:3000/pathname/?search=test#hash"
var loc = new URL("http://example.com:3000/pathname/?search=test#hash")
loc.protocol; // => "http:"
loc.host;     // => "example.com:3000"
loc.hostname; // => "example.com"
loc.port;     // => "3000"
loc.pathname; // => "/pathname/"
loc.hash;     // => "#hash"
loc.search;   // => "?search=test"
url: http://example.com?param=test#param=again

url('?param'); // test
url('#param'); // again
url('protocol'); // http
url('port'); // 80
url('domain'); // example.com
url('tld'); // com

etc...
url = "http://www.example.com/path/to/somwhere";
urlParts = /^(?:\w+\:\/\/)?([^\/]+)(.*)$/.exec(url);
hostname = urlParts[1]; // www.example.com
path = urlParts[2]; // /path/to/somwhere
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: "" }
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://domain.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;
}
var myUrl = new ParsedUrl("http://www.example.com:8080/path?query=123#fragment");
{
    hash: "#fragment"
    host: "www.example.com:8080"
    hostname: "www.example.com"
    href: "http://www.example.com:8080/path?query=123#fragment"
    pathname: "/path"
    port: "8080"
    protocol: "http:"
    search: "?query=123"
}
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");
var t = parserURI("http://user:pass@example.com:8080/directory/file.ext?query=1&next=4&sed=5#anchor");
        $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 ) );
// 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'));
{
  hash: "#fragment",
  host: "www.example.com:8080",
  hostname: "www.example.com",
  href: "http://www.example.com:8080/path?var1=123&amp;var2=abc#fragment",
  pathname: "/path",
  port: "80",
  protocol: "http:",
  search: "?var1=123&amp;var2=abc"
}

"123"
"abc"
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 '';
    };
}