Jon Harding
Jon Harding

Reputation: 4946

Strip protocol and subdomain from a URL

I use the following code to remove http:// and www. or dev. from a URL:

Uri uri = new Uri(this.Referrer);
    if (uri != null )
        return uri.GetLeftPart(UriPartial.Authority).Replace("http://dev.", "").Replace("http://www.", "").Replace("http://", "");
    else
        return null;

I don't like that I'm relying on the .Replace() function. I had a bug for quite a while until I realized that the this.Referrer didn't have the subdomain.

Is there a more elegant way to do this?

Upvotes: 1

Views: 1384

Answers (1)

Mark Walsh
Mark Walsh

Reputation: 3361

You could try using a regex like this:

http:\/\/(.*?)[.?]|http:\/\/

Instead of performing multiple replaces. This would catch any other sub-domains you encounter. I'm not aware of another way you can achieve this.

This is actually not as short as it could be but I wanted to keep it readable.

Upvotes: 1

Related Questions