How would you parse a url in Ruby to get the main domain?

前端 未结 7 633
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 02:03

I want to be able to parse any url with ruby to get the main part of the domain without the www (just the XXXX.com)

相关标签:
7条回答
  • 2020-11-30 02:33

    This should work with pretty much any URL:

    # URL always gets parsed twice
    def get_host_without_www(url)
      url = "http://#{url}" if URI.parse(url).scheme.nil?
      host = URI.parse(url).host.downcase
      host.start_with?('www.') ? host[4..-1] : host
    end
    

    Or:

    # Only parses twice if url doesn't start with a scheme
    def get_host_without_www(url)
      uri = URI.parse(url)
      uri = URI.parse("http://#{url}") if uri.scheme.nil?
      host = uri.host.downcase
      host.start_with?('www.') ? host[4..-1] : host
    end
    

    You may have to require 'uri'.

    0 讨论(0)
提交回复
热议问题