How to get Domain name from URL using jquery..?

后端 未结 10 910
一生所求
一生所求 2020-12-02 10:01

I have domain name for eq.

1) http://www.abc.com/search 
2) http://go.abc.com/work

I get only domain name from the above URL

Output

相关标签:
10条回答
  • 2020-12-02 10:21

    To get the url as well as the protocol used we can try the code below.

    For example to get the domain as well as the protocol used (http/https).

    https://google.com

    You can use -

    host = window.location.protocol+'//'+window.location.hostname+'/';

    It'll return you the protocol as well as domain name. https://google.com/

    0 讨论(0)
  • 2020-12-02 10:26

    While pure JavaScript is sufficient here, I still prefer the jQuery approach. After all, the ask was to get the hostname using jQuery.

    var hostName = $(location).attr('hostname');      // www.example.com
    
    0 讨论(0)
  • 2020-12-02 10:33

    In a browser

    You can leverage the browser's URL parser using an <a> element:

    var hostname = $('<a>').prop('href', url).prop('hostname');
    

    or without jQuery:

    var a = document.createElement('a');
    a.href = url;
    var hostname = a.hostname;
    

    (This trick is particularly useful for resolving paths relative to the current page.)

    Outside of a browser (and probably more efficiently):

    Use the following function:

    function get_hostname(url) {
        var m = url.match(/^http:\/\/[^/]+/);
        return m ? m[0] : null;
    }
    

    Use it like this:

    get_hostname("http://example.com/path");
    

    This will return http://example.com/ as in your example output.

    Hostname of the current page

    If you are only trying the get the hostname of the current page, use document.location.hostname.

    0 讨论(0)
  • 2020-12-02 10:35

    You can do this with plain js by using

    1. location.host , same as document.location.hostname
    2. document.domain Not recommended
    0 讨论(0)
提交回复
热议问题