skip to Main Content

I am trying to seperate or removing a string.
Here the example:

String sample = "https://xyz-api.portal.com/";

i want to get only "xyz-api", this string and want to store a variable,

the expected output = 
String result = "xyz-api"

How to do that, i am confusing this string conversion, please help

3

Answers


  1. You can use the Uri class.

    String sample = 'https://xyz-api.portal.com/';
    String result = Uri.parse(sample).host.split('.')[0];
    print(result);
    

    Result: xyz-api

    Login or Signup to reply.
  2. You can do it like this:

    String url = "https://xyz-api.portal.com";
    
    // Remove https or http from the start of the url.
    url = url.replaceAll('https://', '').replaceAll('http://', '');
    
    // Split the url by the dots. You get a list which should look like this:
    // [“xyz-api”, “portal”, “com”]
    // You then want to take the first element in the list.
    final subdomain = url.split('.')[0];
    
    print(subdomain); // xyz-api
    
    
    Login or Signup to reply.
  3. You can do it like this:

    String sample = "https://xyz-api.portal.com/";
    
    String ans = value.split('.')[0].split('//')[1];
    
    print(ans);// xyz-api
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search