본문 바로가기
알고리즘/Codewars

[Codewars] Extract the domain name from a URL (5 kyu) / JavaScript

by fluss 2022. 10. 21.

https://www.codewars.com/kata/514a024011ea4fb54200004b

 

Codewars - Achieve mastery through coding practice and developer mentorship

Coding practice for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

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"
 

설명:

문자열로 주어진 URL을 도메인 이름만 구분하여 문자열로 반환하는 함수를 작성하세요. 예시:

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

풀이

function domainName(url){
  url = url.replace("http://", "");
  url = url.replace("https://", "");
  url = url.replace("www.", "");
  return url.split(".")[0];
}

replace를 이용해 도메인 이름 앞부분을 제거하고 split으로 '.'을 기준으로 나누어 만들어진 배열의 제일 앞에 있는 원소를 반환한다.

댓글