Extract hostname name from string

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

    Try this:

    var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
    var domain = matches && matches[1];  // domain will be null if no match is found
    

    If you want to exclude the port from your result, use this expression instead:

    /^https?\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i
    

    Edit: To prevent specific domains from matching, use a negative lookahead. (?!youtube.com)

    /^https?\:\/\/(?!(?:www\.)?(?:youtube\.com|youtu\.be))([^\/:?#]+)(?:[\/:?#]|$)/i
    

提交回复
热议问题