How can I parse urls like
http://www.1800contacts.com/productlist.aspx?dl=P&source=cj&ac=8.2.0007
and only get
http://www.1800contacts.com
?
PS. Some urls have subdomains etc so I can't use regexps here.
How can I parse urls like
http://www.1800contacts.com/productlist.aspx?dl=P&source=cj&ac=8.2.0007
and only get
http://www.1800contacts.com
?
PS. Some urls have subdomains etc so I can't use regexps here.
Try to use 'uri' library:
require 'uri'
address = 'http://www.1800contacts.com/productlist.aspx?dl=P&source=cj&ac=8.2.0007'
uri = URI.parse(address)
puts "#{uri.scheme}://#{uri.host}" # => http://www.1800contacts.com
address = 'http://example.com:8080/you-found-me.php'
and it give you following: uri.port # => 8080
–
Demonolatry I like @skojin's answer number 1 (sorry I opened another answer, it's only a long comment) because it makes more general code for both cases:
require 'uri'
uri = URI "http://www.1800contacts.com/productlist.aspx?dl=P&source=cj&ac=8.2.0007"
uri.query = uri.fragment = nil
uri.path = ""
uri.to_s
# => "http://www.1800contacts.com"
uri = URI "http://example.com:8080/you-found-me.php"
uri.query = uri.fragment = nil
uri.path = ""
uri.to_s
# => "http://example.com:8080"
2 alternative ways
uri = URI.parse(url); uri.path = ''; uri.query = nil; uri.to_s
url.split('/')[0,3].join('/')
© 2022 - 2024 — McMap. All rights reserved.