iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 11
1
自我挑戰組

見習村-30 Day CodeWars Challenge系列 第 11

見習村11 - Extract the domain name from a URL

11 - Extract the domain name from a URL

Don't say so much, just coding...

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:

  domain_name("http://github.com/carbonfive/raygun") == "github" 
  domain_name("http://www.zombie-bites.com") == "zombie-bites"
  domain_name("https://www.cnet.com") == "cnet"

Ruby

Init

  def domain_name(url)
    # return just the domain name
  end

Sample Testing

  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")

Javascript

Init

  function domainName(url){
    //your code here
  }

Sample Testing

  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");

Thinking

想法(1): 原本其實是從 URI 的方式寫完的,不過發現要處理的東西有點多,後來覺得 start_with 來解決就可以,也不用 regex 去 metch 所有條件(regex 就爛)
想法(2): 用 gsub 把所有要篩選的條件寫進來也不錯

https://ithelp.ithome.com.tw/upload/images/20200926/20120826iQVDzANvdd.jpg
圖片來源:Unsplash Marvin Meyer

Hint & Reference

Solution

Ruby

  # 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

Javascript

  // Solution 1 gsub to replace XDDD
  function domainName(url){
    return url.replace('http://', '')
              .replace('https://', '')
              .replace('www.', '')
              .split('.')[0];
  }

上一篇
見習村10 - Playing with digits
下一篇
見習村12 - Greed is Dice
系列文
見習村-30 Day CodeWars Challenge30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言