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?
You do not need to make use of RegExp in this case.
Dart has a premade class for parsing URLs:
UriWhat 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With