Extract hostname name from string

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

    function getHostName(url) {
      const urlStart: string = url.includes('//www.') ? '//www.' : '//';
      
      return url.substring(url.indexOf(urlStart) + urlStart.length).split('/')[0];
    };
    
    console.log(getHostName('https://stackoverflow.com/questions')) // stackoverflow.com
    
    console.log(getHostName('stackoverflow.com/questions')) // stackoverflow.com
    

提交回复
热议问题