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

前端 未结 22 1163
南方客
南方客 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:14

    For those looking for a modern solution that works in IE, Firefox, AND Chrome:

    None of these solutions that use a hyperlink element will work the same in chrome. If you pass an invalid (or blank) url to chrome, it will always return the host where the script is called from. So in IE you will get blank, whereas in Chrome you will get localhost (or whatever).

    If you are trying to look at the referrer, this is deceitful. You will want to make sure that the host you get back was in the original url to deal with this:

        function getHostNameFromUrl(url) {
            // Parses the domain/host from a given url.
            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 : '';
        }
    

提交回复
热议问题