Code Snippet
Get URL and URL Parts in JavaScript
JavaScript can access the current URL in parts. For this URL:
http://css-tricks.com/example/index.html
- window.location.protocol = "http"
- window.location.host = "css-tricks.com"
- window.location.pathname = "example/index.html"
So to get the full URL path in JavaScript:
var newURL = window.location.protocol + "://" + window.location.host + "/" + window.location.pathname;If you need to breath up the pathname, for example a URL like http://css-tricks.com/blah/blah/blah/index.html, you can split the string on "/" characters
var pathArray = window.location.pathname.split( '/' );Then access the different parts by the parts of the array, like
var secondLevelLocation = pathArray[0];To put that pathname back together, you can stitch together the array and put the "/"'s back in:
var newPathname = "";
for ( i = 0; i pathArray.length; i++ ) {
newPathname += "/";
newPathname += pathArray[i];
}
Really cool! Thanks!
Just to mention that there was a small error:
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;Should have been:
var newURL = window.location.protocol + "://" + window.location.host + "/" + window.location.pathname;Thanks Ben, fixed that.
Just testing in ff 3.6.10 and window.location.protocol = “http:” so the is the original code (var newURL = window.location.protocol + “//” + window.location.host + “/” + window.location.pathname;) correct ?
I will some day become like you guy, who knows maybe even bettter.
I have a problem in webtrends reporting where the URL of the page isn’t showing up.
The URL below is a pop-up box containing a form, but the current tracking is only capturing up to the ‘?’ and so in the reporting the page name is being displayed as ‘/’ – which of course, is not correct.
The URL is in the format http://www.domain.com/?formpage=9
Is there a way to extract the parameters at the end of this URL?
Thanks,
Chris
How DOES the computer know location.pathname? Can it be a filename.location.pathname instead of window.location.pathname? It is strictly for commercial purposes.
I fix the “:” error
window.location.protocol.replace(/\:/g, ”) + “://” + window.location.host
ie and firefox not send protocol in the same way
hi chris l would like to know how l can get the full url from ” a”(hyperlink) on click and use it with .load javascript . becaus l want to load it in a div thanks
alert($(location).attr(‘hash’));
var fullUrl = window.location.pathname + window.location.search;
alert(fullUrl);
get url with parameters