Extract hostname name from string

后端 未结 28 1503
情歌与酒
情歌与酒 2020-11-22 07:15

I would like to match just the root of a URL and not the whole URL from a text string. Given:

http://www.youtube.co         


        
28条回答
  •  难免孤独
    2020-11-22 08:06

    I personally researched a lot for this solution, and the best one I could find is actually from CloudFlare's "browser check":

    function getHostname(){  
                secretDiv = document.createElement('div');
                secretDiv.innerHTML = "x";
                secretDiv = secretDiv.firstChild.href;
                var HasHTTPS = secretDiv.match(/https?:\/\//)[0];
                secretDiv = secretDiv.substr(HasHTTPS.length);
                secretDiv = secretDiv.substr(0, secretDiv.length - 1);
                return(secretDiv);  
    }  
    
    getHostname();
    

    I rewritten variables so it is more "human" readable, but it does the job better than expected.

提交回复
热议问题