0

I have below urls

1) https://stackoverflow.com/questions/ask?guided=true
2) https://www.youtube.com/watch?v=ClkQA2Lb_iE
3) https://trello.com/b

I need to get only the host name from the above urls. So the output should be

1) stackoverflow
2) youtube
3) trello
Mohammad
  • 21,175
  • 15
  • 55
  • 84
Profer
  • 553
  • 8
  • 40
  • 81

2 Answers2

1

Use pattern /(\w+)\.\w{2,}(\/|\?|$)/ to getting domain name from url. The regex match any string is before / or ?

var getName = function(url){
  return url.match(/(\w+)\.\w{2,}(\/|\?|$)/)[1];
}

console.log(
  getName("https://stackoverflow.com/questions/ask?guided=true"),
  getName("https://www.youtube.com/watch?v=ClkQA2Lb_iE"),
  getName("https://trello.com")
) 
Mohammad
  • 21,175
  • 15
  • 55
  • 84
  • Hi for this one `https://www.google.co.in/` I am getting only `co`... Could you pls check this – Profer May 07 '19 at 16:50
  • @Profer You'r right. It is because there isn't a right solution to detecting domain name using regex or parsers. Even javascript [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object that parse url return `google.co.in` as **hostname** and does not return `google`. I think you have list of domain suffix to do this work. – Mohammad May 07 '19 at 19:38
  • So it is not possible? I have to take full url `google.co.in` ? – Profer May 08 '19 at 05:24
  • @Profer I can't find any solution for it, you can only get hostname contain domain suffix – Mohammad May 08 '19 at 05:52
1

You can get a host name like so, without Regex.

const getHostFromUrl = (url: string): string => {
  return new URL(url).hostname.replace("www.", "");
};

getHostFromUrl('https://www.youtube.com/watch?v=ClkQA2Lb_iE') // youtube.com
mrded
  • 4,674
  • 2
  • 34
  • 36