Extract hostname name from string

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

    My code looks like this. Regular expressions can come in many forms, and here are my test cases I think it's more scalable.

    function extractUrlInfo(url){
      let reg = /^((?http[s]?):\/\/)?(?((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])|[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)))(\:(?[0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]))?$/
      return reg.exec(url).groups
    }
    
    var url = "https://192.168.1.1:1234"
    console.log(extractUrlInfo(url))
    var url = "https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string"
    console.log(extractUrlInfo(url))

提交回复
热议问题