Strip protocol and subdomain from a URL

2019-07-31 17:19发布

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?

标签: c# url
1条回答
叛逆
2楼-- · 2019-07-31 17:40

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.

查看更多
登录 后发表回答