0

How do I turn this:

http://bit.ly/Wn2Xdz

into this:

http://bit.ly/

Bear in mind that this would NOT be the current URL in the window, but a string. And the base URL might change (not all the time http://bit.ly).

TheBigDoubleA
  • 432
  • 2
  • 7
  • 26
  • Warning: If your website is ever hosted as a web application (under a path like domain.com/appname/) a simple string indexing answer will not work. – iCollect.it Ltd Oct 20 '14 at 09:57
  • http://stackoverflow.com/questions/8498592/extract-root-domain-name-from-string – Nishan Senevirathna Oct 20 '14 at 09:59
  • possible duplicate of [How can I turn a string into a Location object?](http://stackoverflow.com/questions/6736595/how-can-i-turn-a-string-into-a-location-object) – Tudmotu Oct 20 '14 at 10:00
  • http://stackoverflow.com/questions/6736595/how-can-i-turn-a-string-into-a-location-object – Tudmotu Oct 20 '14 at 10:01
  • @TrueBlueAussie "web applications that are not hosted at the domain root" what is this restriction? Question was not subjected to that kind of restriction right? – Nishan Senevirathna Oct 20 '14 at 10:05
  • @Nishan Senevirathna: Question is not clear, but I already removed that comment as it may well be the simplest case only. Most answers will not cover the case of a web-app. – iCollect.it Ltd Oct 20 '14 at 10:09

3 Answers3

2

you can use an anchor tag to parse it reliably:

var temp=document.createElement("a"); 
temp.href="http://bit.ly/Wn2Xdz"; 
alert(temp.origin+"/"); // shows: "http://bit.ly/"
dandavis
  • 16,370
  • 5
  • 40
  • 36
2

I'd suggest, at its simplest:

function hostnameFromURL(url) {
  var a = document.createElement('a');
  a.href = url;
  return a.protocol + '//' + a.hostname;
}

console.log(hostnameFromURL('http://bit.ly/Wn2Xdz')); // http://bit.ly
David Thomas
  • 249,100
  • 51
  • 377
  • 410
0

If it is just a string manipulation thing, you can get the base url from given string as below

var url = "http://bit.ly/Wn2Xdz";
var temp = url.split("/");
var baseUrl = temp[0] + "//" + temp[2];//http://bit.ly
Amitesh
  • 1,507
  • 1
  • 11
  • 19
  • No this is not a simple one as string manipulation. Sometime you can get complex urls with port like 8080 or something else. So you can't rely on this. – Nishan Senevirathna Oct 20 '14 at 10:26