This is the simplest solution to the Code Wars kata Problem I solved today.
Here is the instruction:
Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example:
* url = "http://github.com/carbonfive/raygun" -> domain name = "github"
* url = "http://www.zombie-bites.com" -> domain name = "zombie-bites"
* url = "https://www.cnet.com" -> domain name = cnet"
Here is the solution:
function domainName(url){
url = url.replace("http://"," " );
url = url.replace("http://"," " );
url = url.replace("www"," ");
return url.split(".")[0]
console.log(url)
}
The function input is taken as the URL and the first part of the domain i.e subdomain and the protocol is replaced with a blank space. We take all possible cases that the URL might be beginning with and substitute it with a blank space.
After that, the domain will have been stripped down to look like this:
domain.port.path.parameters
i.e
google.com
google.co.ke:80/videoplay....
We then split the remaining part of the domain at the full stop point and all return the first part of the split domain.
When the function is called, this is the outcome.
domainName("http://google.co.jp")
output: google