Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse domain name from URL string

How would I parse a domain name in Objective-C?

For example if my string value was "http://www.google.com" I would like to parse out the string "google"

like image 370
dubbeat Avatar asked May 18 '26 09:05

dubbeat


1 Answers

I think the question is a tiny bit invalid. A host is determined by its FQDN (fully qualified domain name) which, in your example, is www.google.com. It's not the same as mail.google.com or www.google.info or google.com. To single out "google" is not trivial and does not make much sense from URL perspective.

If you'd like to just parse the URL more-or-less intelligently, I think you can do the following:

  1. Use NSURL's -host method to get the scheme and path/query stripped correctly.
  2. Use NSString's -componentsSeparatedByString: method to get an array of the domain name's "components".
  3. Ignore the last component.
  4. If there's only one component left (or it may be enough to take the second-last component), you're done.
  5. If the first component contains "www" like www3, "ftp", "mail" or something of their kind, you can ignore it too if you like. The rest may be of interest, depending on your needs.
  6. Test your algorithm against ten thousand URLs to get a sense of futility of this task ;)
like image 53
Costique Avatar answered May 20 '26 01:05

Costique



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!