Monday, March 22, 2010

Get the URL with Javascript

It's good to get questions from your work colleges, and specially those you can't answer right away, so you're forced to do some research.

Today one person asked me if I know a way to get the URL of a page using Javascript. I don't recall doing it before. With PHP (and its $_URL, $_POST, $_REQUEST, $_SERVER, etc variables) I never needed of JS for such task.

But it's always useful to know it and have code like the following handy:

function getHost() {
var url = window.location;
var urlparts = url.split('/');
var host = urlparts[0];
alert(host);
}

Credits go to CNET.

No comments:

Post a Comment