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!
Is there any way to extract the urls in search engine when user enters a key word in search engine by using java script….
if yes plz mail me or send me a message to 9492936947
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 ?
is it possible context path…? i hope its not in browser script
Eg: http://www.kalidass.com/core
core is my context path.
It ll be change in feature
Hey,
I am getting two colons while using
working fine with
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
How to grab the page URL when submitting enquiry form
I’m a newbie who’s stuck trying implement something like this form a web form
Can someone please provide an example of how this could be done?
Thanks!!
Hi there,
this is not working very well if you send a querystring like “?test=abc/def” to the splitting function. How to avoid that?
Christoph
use ‘document.URL’ for getting the full path of the current web page.
Looks like you’re missing the query/search parameters and the hash. This will get you those. :)
var newURL = window.location.protocol + “://” + window.location.host + “/” + window.location.pathname + window.location.search + window.location.hash;
Thanks for the post, found the info I was looking for.
In the code for putting it back together: don’t forget the < in the for declaration:
And to shorten this up, you could just do this:
Hi guys,
I’m an uber-newbie. Would this js be useful for capturing the URL a user typed in and then sending them to an appropriate style sheet based on that URL?
Thanks – any comments/direction would be awesome..
to access array from right to left:
secondLevelLocation[secondLevelLocation.length-1]
Um, this is AWESOME.. thanks Chris.
I think you had it right the first time…
When I use your FULL URL code, I get:
http:://staging.site.com//Registration.aspx
Double : and double /
Is it a browser thing (using Chrome)?
Anyway, thanks!
Essentially what I’m trying to do is a video setup, where my url would be
http://myweb.site/blah/blah/blah?video=mp4:Video2.mp4
and I want to just grab mp4:Video2.mp4 as a variable to use in javascript.
This URL will always be the same (besides after the = symbol) so would my code end up being something like this?
I think that most browsers return window.location.pathname with a slash in front as that is what they are supposed to do by W3C spec.
It would be best to update the “var newURL” example to check for existing slash rather than adding it in right away.
(http://www.w3.org/TR/Window/#location-attributes)
you can just use “location” ex.
var newURL = location
Thanks for the Information :D
Hello, I need to do something very similiar. If anyone could help please.
I need a script that will extract the subdomain and add it to a new domain name to create a url that will open in a new window when clicked on.
So From This:
http://subdomain.domain.com
To This:
http://newdomain.com/subdomain
window.top.location.replace(“http://newdomain.com/”+window.location.host.split(‘.’)[0]);
Hope Sandra will find a solution with this.
http://localhost/xg/xg.php#home
http://localhost/xg/xg.php#group-text
i want to get #home and #group-text and rest of the div ids in my url in php
how it will be possible?
Hai there, for Mannan, may be you can try use :
var url=document.URL.split(‘#’)[1];
it will return group-text..
btw, good article.. :D
my blog
Hey pal, thank you for your posting. I need it for my JS project.
Best regards,
Anton
Hi Everyone,
I guess there is still an error ( well, actually i get one using Safari / Firefox / Chrome on the mac platform):
The long-hand version should be:
or even (if I am right in the order) :
For the short-hand versions:
After testing, they seems to work cross-browsers (..)
>Btw I was desperate to find a solution to my problem (getting a [object object] instead of an URL ;p ), and I think now I can dig it deeper & debug it out (at least)
I rarely post , but I sure follow ;p
So thanks again Chris, and all the others for the info(s)
This much helpful for me. Thanks
Really useful quick reference Chris, thanks!
Would it be worth adding window.location.search and window.location.port in there too :)?
Might want to add a < or some kind of operator into that for loop:
for ( i = 0; i pathArray.length; i++ ) {
fwiw
Fixed, thanks.
var newURL = window.location.protocol + “://” + window.location.host + “/” + window.location.pathname + “?” + window.location.search + window.location.hash;
This is the full URL, it handles php events (something.php?blah=blah) and also breaks(Hashes) (like YouTube uses to detect your location in a video) Youtube.com/#videolocation=35 (Thats an example, I don’t think that’s how they actually do it off the top of my head but I do know they use pound signs haha)
Some comments above could be added to! I completely forgot about window.location.port! Nice!
this should work on all browsers
(changes url from .html to .php, including double : fix)
var newurl = window.location.protocol.replace(/\:/g,'') + "://" + window.location.host + window.location.pathname.replace(/html/g,'php');sorry, mixed syntax, better like this
var newurl = window.location.protocol.replace(/\:/g,'') + '://' + window.location.host + window.location.pathname.replace(/html/g,'php');You forgot to the comparison term in the for loop…
Thanks for your post anyway ^^
Love U Chris…
Thanks for this post, as it was very helpful. I have a question in regards to parsing out everything after the “/” in the domain. Example if I have this domain http://www.google.com/patents/US20120211565. Is there a way to parse out the US20120211565 using a similar script???
Thanks for you assistance in advanced
var pathArray = window.location.pathname.split( '/' );
//["", "patents", "US20120211565"]
pathArray[2];
//US20120211565
Using the pop method for your array would get the end if you don’t want to have to specify the index and you know it is the everything after the last ‘/’ that you want to get.
Notice on pages like this one, it ends in a ‘/’ so there is nothing after the last ‘/’
Maybe you have a url already stored in a variabled called myURL. Then you could do something like
Thank you Milo! I have an additional question hopefully you can assist. Essentially what I’m doing is this: I have about 700+ QR codes… each code has a link to a specific Patent (the google patents url provided above). I’m writing a program that when the QR code is scanned you will be directed to the patent in the same page you scanned from using an iframe (so you can continuously scan without exiting that page). The issue is Google doesn’t allow any of their pages to be embedded iframes. The solution, I’ve downloaded all the patent PDFs and renamed each to match the associated QR patent URL. When scanned, I want to take the URL and parse out the patent # and replace it with the PDF. (Hope that makes sense)
Question: Because I will be pulling multiple patent #’s, does the code you provided above still apply? Or will this code need to be tweaked???
Thanks for your assistance!
yes you can access iframes from parent document or parent document from within an iframe. look at window object or google acessing frames or parent doc from inside frame. then just do something like window.location.href = lastChunk + ‘.pdf’ or whatever path the pdfs live in
Thanks again… I was able to figure it out. This is what I did:
var tokenString = data.split('/'); var filename = tokenString[tokenString.length - 1]; var MainURL = 'http://www.domain.com/patents/pdf/' + filename + '.pdf'; document.getElementById('MainURLtextarea').innerHTML = MainURL; document.getElementById("MainURLtextarea").innerHTML = '';Again… I appreciate your assistance… helped me find a solution!
Hey Chris Coyier, Ben Chapman is wrong, or browsers have changed since then. There shouldn’t be an added colon.
Yep, just tested in Chrome Version 25.0.1364.172 m, Firefox Version 19.0.2 and Internet Explorer Version 10.0.9200.16521 and from the consoles of all three, window.location.protocol contains “http:” with the colon. I would be surprised to learn that had changed in recent years. http://stackoverflow.com/questions/4723213/detect-http-or-https-then-force-https-in-javascript is from 2011-01-18 and appears it contained a colon then.
Alrighty, putting back to original.
Hi Chris,
Is there a way to use that code to grab part of a Dynamic URL string and insert into a tracking code so I can track where leads and conversions came from?
It would need to go in the html code here where the value= would be what is dynamic.
And the URL string would be http://mywebsite.com/?c1=csid and the [csid] would be the variable that changes depending on where the traffic came from
such as http://mywebsite.com/?c1=csid becomes http://mywebsite.com/?c1=http://anywebsite.com
and the http://anywebsite.com is what would be needed to be inserted into the value= part
Any help would be appreciated.
Just noticed when I inserted the code, it disappeared from my comment. the html code it would have to be inserted into would look like this “input type=”hidden” name=”TrackerName” value=”test/” ”
Let me see if this gets through
This function should be help specially when we use a local server:
function getBaseURL() {
var url = location.href; // entire url including querystring - also: window.location.href;
var baseURL = url.substring(0, url.indexOf('/', 14));
if (baseURL.indexOf('http://localhost') != -1) {
// Base Url for localhost
var url = location.href; // window.location.href;
var pathname = location.pathname; // window.location.pathname;
var index1 = url.indexOf(pathname);
var index2 = url.indexOf("/", index1 + 1);
var baseLocalUrl = url.substr(0, index2);
return baseLocalUrl + "/";
}
else {
// Root Url for domain name
return baseURL + "/";
}
}