This has come up several times. People have complex URLs with querystring parameters and different protocols (e.g. http:// and https://) stored in a database, flat file, or user-entered, and they want to return just the domain name portion of the URL. Split() is a wonderful function:
<% Function ParseDomainFromURL(url) urlParts = split(url,"/") ParseDomainFromURL = urlParts(2) End Function complexURL = "http://foo.com/whatever.asp?foo=1&bar=2" domain = parseDomainFromURL(complexURL) response.write "Domain = <b>" & domain & "</b>" %> |
This function assumes that you are going to pass a valid URL, with a // preceding the domain name. You can check for this first by testing within the function:
<% Function ParseDomainFromURL(url) if instr(url, "//") > 0 then urlParts = split(url,"/") ParseDomainFromURL = urlParts(2) else ParseDomainFromURL = "Invalid URL" end if End Function %> |
Note that we don't use a split on the double // character sequence, because splitting on single / allows us to isolate just the domain name in one step, and also allows us to avoid having to special-case the scenario where the URL doesn't have any other slashes (e.g. 'http://www.foo.com').