Stripping URLs of their path, query and fragment

Sometimes you might want to strip a URL back so it has no path, parameter, query or fragment. e.g. to go from:;param?query#fragment


We do this a few places in Sandvox. Generally for canonicalisation purposes.

NSURLComponents (and of course KSURLComponents) makes this quite a straightforward task; you simply have to clear out or adjust the components you don't want (in the above example, NSURLComponents treats the parameter component as part of the path).

But if you want something terser, and which works on all releases of Cocoa (and of course makes you feel smartly smug, or smugly smart), here's a nice little one-liner:

We actually include this in KSURLUtilities in the form of -[NSURL ks_hostURL] if that suits your needs too.

One possible drawback: if you are using this technique for generating canonical URLs, any information before the path (i.e. the scheme and authority component) will be left untouched. So if you want to strip out things like user names, then NSURLComponents or KSURLComponents is your best bet.

Thanks to Daniel Tull for prompting me to publish this tip :)

© Mike Abdullah 2007-2015