Don't say so much, just coding...
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:
domain_name("http://github.com/carbonfive/raygun") == "github"
domain_name("http://www.zombie-bites.com") == "zombie-bites"
domain_name("https://www.cnet.com") == "cnet"
def domain_name(url)
# return just the domain name
end
Test.assert_equals(domain_name("http://google.com"), "google")
Test.assert_equals(domain_name("http://google.co.jp"), "google")
Test.assert_equals(domain_name("www.xakep.ru"), "xakep")
Test.assert_equals(domain_name("https://youtube.com"), "youtube")
function domainName(url){
//your code here
}
Test.assertEquals(domainName("http://google.com"), "google");
Test.assertEquals(domainName("http://google.co.jp"), "google");
Test.assertEquals(domainName("www.xakep.ru"), "xakep");
Test.assertEquals(domainName("https://youtube.com"), "youtube");
想法(1): 原本其實是從 URI
的方式寫完的,不過發現要處理的東西有點多,後來覺得 start_with
來解決就可以,也不用 regex
去 metch 所有條件(regex 就爛)
想法(2): 用 gsub
把所有要篩選的條件寫進來也不錯
# Solution 1
def domain_name(url)
url = url.start_with?('www.') ? url.split('www.').last : url.split('//').last
url.split('.').first
end
# Solution 2
def domain_name(url)
url.start_with?('www.') ? url.split('www.').last.split('.').first
: url.split('//').last.split('.').first
end
# Solution 3
def domain_name(url)
url.gsub('http://', '')
.gsub('https://', '')
.gsub('www.', '')
.split(".")[0]
end
// Solution 1 gsub to replace XDDD
function domainName(url){
return url.replace('http://', '')
.replace('https://', '')
.replace('www.', '')
.split('.')[0];
}