Extract hostname name from string

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

    in short way you can do like this

    var url = "http://www.someurl.com/support/feature"
    
    function getDomain(url){
      domain=url.split("//")[1];
      return domain.split("/")[0];
    }
    eg:
      getDomain("http://www.example.com/page/1")
    
      output:
       "www.example.com"
    

    Use above function to get domain name

    0 讨论(0)
  • 2020-11-22 08:18

    Just use the URL() constructor:

    new URL(url).host
    
    0 讨论(0)
  • 2020-11-22 08:18
    function hostname(url) {
        var match = url.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/i);
        if ( match != null && match.length > 2 && typeof match[2] === 'string' && match[2].length > 0 ) return match[2];
    }
    

    The above code will successfully parse the hostnames for the following example urls:

    http://WWW.first.com/folder/page.html first.com

    http://mail.google.com/folder/page.html mail.google.com

    https://mail.google.com/folder/page.html mail.google.com

    http://www2.somewhere.com/folder/page.html?q=1 somewhere.com

    https://www.another.eu/folder/page.html?q=1 another.eu

    Original credit goes to: http://www.primaryobjects.com/CMS/Article145

    0 讨论(0)
  • 2020-11-22 08:18

    Try below code for exact domain name using regex,

    String line = "http://www.youtube.com/watch?v=ClkQA2Lb_iE";

      String pattern3="([\\w\\W]\\.)+(.*)?(\\.[\\w]+)";
    
      Pattern r = Pattern.compile(pattern3);
    
    
      Matcher m = r.matcher(line);
      if (m.find( )) {
    
        System.out.println("Found value: " + m.group(2) );
      } else {
         System.out.println("NO MATCH");
      }
    
    0 讨论(0)
提交回复
热议问题