4

For Example I have this string

http://www.merriam-webster.com/dictionary/sample

What I want is to return only merriam-webster.com I'm planning to use .Replace() but I think there are better approach for this question.

ajbee
  • 3,511
  • 3
  • 29
  • 56

5 Answers5

6

If you are working for Winforms then

string url = "http://www.merriam-webster.com/dictionary/sample";

UriBuilder ub = new UriBuilder(url);

MessageBox.Show(ub.Host.Replace("www.",""));

and for web,

Get host domain from URL?

Community
  • 1
  • 1
Angad
  • 82
  • 4
4

How about this

System.Uri uri = new Uri("http://stackoverflow.com/search?q=something");
string uriHost = uri.Host;

?

Roman
  • 568
  • 3
  • 8
  • 20
  • 1
    Uri.Host still returns the www, but I think I will just use .Replace with that problem – ajbee Jun 09 '16 at 03:55
2

Answers here don't handle the case like "http://abcwww.com". Check if the url starts with 'www.' before replacing it.

if (url.StartsWith("www.", StringComparison.OrdinalIgnoreCase))
    url = url.Replace("www.", string.Empty);
Owen
  • 4,229
  • 5
  • 42
  • 50
jayasurya_j
  • 1,519
  • 1
  • 15
  • 22
  • can you explain how it will fail? – jayasurya_j Nov 08 '19 at 05:32
  • Ahh StackOverflow removed the http & www. from my original comment above. Was trying to say it fails for "http//www.merriam-websterwww.com/dictionary/sample". It returns merriam-webstercom. https://dotnetfiddle.net/DSAHnU. – Owen Nov 09 '19 at 13:44
  • I went for url = url.Remove(0,4); – Owen Nov 09 '19 at 13:51
1

You can use this:

        var a = "http://www.merriam-webster.com/dictionary/sample";
        var b = a.Split('.');
        var c = b[1] +"."+ b[2].Remove(3);
Hamed
  • 590
  • 5
  • 16
0

You can leverage System.Uri class:

System.Uri uri = new Uri("https://www.google.com/search?q=something");
string uriWithoutScheme = uri.Host + uri.PathAndQuery + uri.Fragment;

Or you can use below:

UriBuilder ub = new UriBuilder("https://www.google.com/search?q=something");
currentValue = ub.Host.Replace("www.", "");
Arun Sharma
  • 869
  • 9
  • 9