0

I know that many people have already posted this, including hyperrjas, but they always are looking to transform http://example.com/fawoefj/faeewjfp into a domain like this: http://example.com.

However, I would like it to transform into a domain like: example.com

Community
  • 1
  • 1
Chris Happy
  • 7,088
  • 2
  • 22
  • 49
  • 1
    The link you posted gives you exactly the answer. – Steve Oct 31 '16 at 05:41
  • @Steve I tried it and it gave `http://example.com`, not `example.com` – Chris Happy Oct 31 '16 at 05:43
  • You don't have to use the answer exactly as written, look closer and see what is being returned. (hint: `this.protocol` returns `http:`) – Steve Oct 31 '16 at 05:44
  • @Steve Aww... I see. Change it to `...text(this.host)`. Thanks for the hint, KhaledMohamedP also pushed me in the right direction. If you make an answer, I'll accept it since you help first, but until then... – Chris Happy Oct 31 '16 at 05:50
  • @ChrisHappy hey I posted an answer since you said it was helpful. I have also added magic regex which I think* it will work for all urls – KhaledMohamedP Oct 31 '16 at 06:05

1 Answers1

2

the following can help you get the hostname

window.location.host

also if you are a regex fan like I am, this will work:

urlString = "http://stackoverflow.com/posts/40337155/"

urlString.replace(/^(http|https):\/\//, '').replace(/\/.+/, '');
KhaledMohamedP
  • 5,000
  • 3
  • 28
  • 26
  • Thanks for your answer, but I'm not accepting it because I was trying to get the host name of a link, not the current window. (I don't have much experience with regex. – Chris Happy Oct 31 '16 at 06:11
  • @ChrisHappy it's ok. The regex posted is not fully tested anyway. I would love to see where it actually fails though . Hope you find the right answer :) – KhaledMohamedP Oct 31 '16 at 06:15
  • 1
    I got it, after your and Steve's hint, my final code was `$("a").each(function(){ $(this).text(this.host); });` – Chris Happy Oct 31 '16 at 06:21
  • Thanks for the answer! This removes the full path if there is one, but leaves the trailing slash if there isn't one ... `http://example.com/` becomes `example.com/` ... you need this to remove the lone single slash `.replace(/\/.*/, '');` – Dazza Feb 07 '23 at 00:00