我想拿一根绳子

var a = "http://example.com/aa/bb/"

然后把它加工成一个物体

a.hostname == "example.com"

and

a.pathname == "/aa/bb"

当前回答

为什么不用呢?

        $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 ) );

其他回答

怎么样?

'https://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript'.split('//').pop() .split('/')[0]

结果:

“stackoverflow.com”

你也可以使用来自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'
}

对于那些正在寻找在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 : '';
    }

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);

这不会解析查询和散列,但除此之外它工作得很好。

const getURIParts = (url) => { const matches = url.match(/^(\w+?:\/\/)?([\w-\.]+(?=\/?))?:?(\d*)?([^:]*)/) return { scheme: matches ? matches[1] : undefined, host: matches ? matches[2] : '', port: matches ? matches[3] : undefined, pathname: matches ? matches[4] : '' } } console.log(getURIParts("")) console.log(getURIParts("http://localhost/bla")) console.log(getURIParts("https://api.spotify.com/")) console.log(getURIParts("https://api.spotify.com")) console.log(getURIParts("wss://wss.slack.com/link/?ticket=1234-5678")) console.log(getURIParts("localhost")) console.log(getURIParts("localhost/bla")) console.log(getURIParts("localhost/")) console.log(getURIParts("api.spotify.com/bla/two")) console.log(getURIParts("api.spotify.com:8000/bla/two")) console.log(getURIParts("https://api.spotify.com:8800/")) console.log(getURIParts("/mp3-preview/f504e6b8e037771318656394f532dede4f9bcaea"))