Extract hostname name from string

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

    A neat trick without using regular expressions:

    var tmp        = document.createElement ('a');
    ;   tmp.href   = "http://www.example.com/12xy45";
    
    // tmp.hostname will now contain 'www.example.com'
    // tmp.host will now contain hostname and port 'www.example.com:80'
    

    Wrap the above in a function such as the below and you have yourself a superb way of snatching the domain part out of an URI.

    function url_domain(data) {
      var    a      = document.createElement('a');
             a.href = data;
      return a.hostname;
    }
    

提交回复
热议问题