How do I parse a URL into hostname and path in javascript?

前端 未结 22 1129
南方客
南方客 2020-11-21 22:38

I would like to take a string

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

and process it into an object such that

a.hostname == \         


        
22条回答
  •  甜味超标
    2020-11-21 23:06

    Why do not use it?

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

提交回复
热议问题