5

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.

2
  • You can see this link Commented Jun 9, 2016 at 3:48
  • Where is this value came from? Commented Jun 9, 2016 at 3:48

6 Answers 6

7

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?

Sign up to request clarification or add additional context in comments.

1 Comment

what if the url is something like this http://www.merriam-websterwww.com/dictionary/sample ?
7

How about this

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

?

1 Comment

Uri.Host still returns the www, but I think I will just use .Replace with that problem
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);

Comments

1

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);

3 Comments

can you explain how it will fail?
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. dotnetfiddle.net/DSAHnU.
I went for url = url.Remove(0,4);
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.", "");

Comments

-1

You can use Uri to get the beginning of the URL

string urlWithoutQueryString = new Uri("https://test.com/page?argument=value").GetLeftPart(UriPartial.Path);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.