Extract hostname name from string

后端 未结 28 2018
情歌与酒
情歌与酒 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:18

    function hostname(url) {
        var match = url.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/i);
        if ( match != null && match.length > 2 && typeof match[2] === 'string' && match[2].length > 0 ) return match[2];
    }
    

    The above code will successfully parse the hostnames for the following example urls:

    http://WWW.first.com/folder/page.html first.com

    http://mail.google.com/folder/page.html mail.google.com

    https://mail.google.com/folder/page.html mail.google.com

    http://www2.somewhere.com/folder/page.html?q=1 somewhere.com

    https://www.another.eu/folder/page.html?q=1 another.eu

    Original credit goes to: http://www.primaryobjects.com/CMS/Article145

提交回复
热议问题