Extract hostname name from string

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

    Was looking for a solution to this problem today. None of the above answers seemed to satisfy. I wanted a solution that could be a one liner, no conditional logic and nothing that had to be wrapped in a function.

    Here's what I came up with, seems to work really well:

    hostname="http://www.example.com:1234"
    hostname.split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.')   // gives "example.com"
    

    May look complicated at first glance, but it works pretty simply; the key is using 'slice(-n)' in a couple of places where the good part has to be pulled from the end of the split array (and [0] to get from the front of the split array).

    Each of these tests return "example.com":

    "http://example.com".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.')
    "http://example.com:1234".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.')
    "http://www.example.com:1234".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.')
    "http://foo.www.example.com:1234".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.')
    

提交回复
热议问题