Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart extract host from URL string

Supposing that I have the following URL as a String;

String urlSource = 'https://www.wikipedia.org/';

I want to extract the main page name from this url String; 'wikipedia', removing https:// , www , .com , .org part from the url.

What is the best way to extract this? In case of RegExp, what regular expression do I have to use?

like image 224
SLendeR Avatar asked Dec 18 '22 12:12

SLendeR


1 Answers

You do not need to make use of RegExp in this case.

Dart has a premade class for parsing URLs:

Uri

What you want to achieve is quite simple using that API:

final urlSource = 'https://www.wikipedia.org/';

final uri = Uri.parse(urlSource);
uri.host; // www.wikipedia.org

The Uri.host property will give you www.wikipedia.org. From there, you should easily be able to extract wikipedia.

Uri.host will also remove the whole path, i.e. anything after the / after the host.

Extracting the second-level domain

If you want to get the second-level domain, i.e. wikipedia from the host, you could just do uri.host.split('.')[uri.host.split('.').length - 2].

However, note that this is not fail-safe because you might have subdomains or not (e.g. www) and the top-level domain might also be made up of multiple parts. For example, co.uk uses co as the second-level domain.

like image 93
creativecreatorormaybenot Avatar answered Dec 28 '22 19:12

creativecreatorormaybenot