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
1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Hi for this one https://www.google.co.in/ I am getting only co... Could you pls check this
@Profer You'r right. It is because there isn't a right solution to detecting domain name using regex or parsers. Even javascript 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.
So it is not possible? I have to take full url google.co.in ?
@Profer I can't find any solution for it, you can only get hostname contain domain suffix
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.