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

6

3 Answers 3

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/"
Sign up to request clarification or add additional context in comments.

1 Comment

Very clever solution. Unlike David's this includes the port too
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

Comments

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

1 Comment

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.

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.