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