function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ryan Thomas 317Ryan Thomas 317 

parse domain from url with apex

We have a Sites page with a form with one question asking for the applicant's website url. 
Instead of accepting the website provided, we are trying to pull out the domain from the provided url.  So if someone types in http://www.test.com/ or https://www.test.com/ or www.test.com/test1234, we'd want to use apex to insert the domain only (test.com).  Can anyone help?
Best Answer chosen by Ryan Thomas 317
Raj VakatiRaj Vakati
here is the code Ryan 
 
String ex1 ='http://www.test.com';
String ex2='https://www.test.com/';
String exe3 ='www.test.com/test1234';

String res1 = ex1.replaceFirst('^(https?://)?(www\\.)?', '').split('/')[0]; 
String res2 =ex2.replaceFirst('^(https?://)?(www\\.)?', '').split('/')[0]; 
String res3 = exe3.replaceFirst('^(https?://)?(www\\.)?', '').split('/')[0]; 

System.debug(res1);
System.debug(res2);
System.debug(res3);

 

All Answers

Raj VakatiRaj Vakati
here is the code Ryan 
 
String ex1 ='http://www.test.com';
String ex2='https://www.test.com/';
String exe3 ='www.test.com/test1234';

String res1 = ex1.replaceFirst('^(https?://)?(www\\.)?', '').split('/')[0]; 
String res2 =ex2.replaceFirst('^(https?://)?(www\\.)?', '').split('/')[0]; 
String res3 = exe3.replaceFirst('^(https?://)?(www\\.)?', '').split('/')[0]; 

System.debug(res1);
System.debug(res2);
System.debug(res3);

 
This was selected as the best answer
Ryan Thomas 317Ryan Thomas 317
We will only receive 1 website but each submission has a different url format (http, https, www, etc).  We're trying to take the provided url in the Sites form and strip out the domain.  Is that possible?
Raj VakatiRaj Vakati
change that regular expression .. it will take care of all the format .. HTTP, https, www, etc will work in your case .. 
Taras BabynTaras Babyn
String urlToParse = 'https://developer.salesforce.com/forums/?id=9060G0000005fh2QAA';
String url = urlToParse+'/'; // to handle https://developer.salesforce.com url
String domain = url.substringBetween('://', '/');
System.debug(domain)
// developer.salesforce.com