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];
}

Comments

  1. User Avatar
    Montana Flynn
    Permalink to comment#

    Really cool! Thanks!

    • User Avatar
      svs teja
      Permalink to comment#

      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

    • User Avatar
      Nishan
      Permalink to comment#

      What if i want to pull only the part after the .html
      For example the url example.com/abc.htm#next-section

      I want to pull only “next-section”

      Thanks,
      Nishan

    • User Avatar
      Shyam Makwana
      Permalink to comment#

      @Nishan

      It’s very easy by native JavaScript.

      window.location.hash.split('#')[1]
      
    • User Avatar
      Nodebuck
      Permalink to comment#

      @Shyam Makwana

      For the sake of completeness, you can also do it via document.location:

      document.location.hash
      
    • User Avatar
      Nodebuck
      Permalink to comment#

      Ugh, I meant window.location

      window.location.hash
      

      Even though both work, window.location is the safer way…

  2. User Avatar
    Ben Chapman
    Permalink to comment#

    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;

    • User Avatar
      Chris Coyier
      Permalink to comment#

      Thanks Ben, fixed that.

    • User Avatar
      CIDIC
      Permalink to comment#

      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 ?

    • User Avatar
      kalidass
      Permalink to comment#

      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

    • User Avatar
      Miqdad
      Permalink to comment#

      Hey,

      I am getting two colons while using

      
      var newURL = window.location.protocol + "://" + window.location.host + "/" + window.location.pathname;
      
      

      working fine with

      
      var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
      
      
    • User Avatar
      Chris22

      @Chris, you are still missing the colon before the forward slashes in your code: "://"

  3. User Avatar
    Rosell
    Permalink to comment#

    I will some day become like you guy, who knows maybe even bettter.

  4. User Avatar
    Chris
    Permalink to comment#

    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

    • User Avatar
      A. Nonny Mouse
      Permalink to comment#

      Use document.URL , split on the /’s and pick the last in the array.

  5. User Avatar
    N
    Permalink to comment#

    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.

  6. User Avatar
    David
    Permalink to comment#

    I fix the “:” error

    window.location.protocol.replace(/\:/g, ”) + “://” + window.location.host

    ie and firefox not send protocol in the same way

  7. User Avatar
    kougi
    Permalink to comment#

    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

  8. User Avatar
    sre
    Permalink to comment#

    alert($(location).attr(‘hash’));

  9. User Avatar
    Reza Baiat
    Permalink to comment#

    var fullUrl = window.location.pathname + window.location.search;
    alert(fullUrl);

    get url with parameters

  10. User Avatar
    Luke
    Permalink to comment#

    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!!

  11. User Avatar
    Christoph Neymeyr
    Permalink to comment#

    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

  12. User Avatar
    Manish Madhukar
    Permalink to comment#

    use ‘document.URL’ for getting the full path of the current web page.

  13. User Avatar
    David Calhoun
    Permalink to comment#

    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;

  14. User Avatar
    Kevin
    Permalink to comment#

    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:

    var newPathname = "";
    for ( i = 0; i < pathArray.length; i++ ) {
      newPathname += "/";
      newPathname += pathArray[i];
    }
    

    And to shorten this up, you could just do this:

     var newPathname = pathArray.join("/");
  15. User Avatar
    Frank
    Permalink to comment#

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

    • User Avatar
      Zackery G
      Permalink to comment#

      Hi Frank!

      You certainly could do that! But, it may be easier to keep 1 stylesheet and just append the class name to the body. You can google proper syntax here as I am a little short of time, but…

      var url = window.location.pathname; \\ Or whatever...
      if (url === "whatever.html") { \\ THREE Equal Signs
          document.getElementsByTagName('body')[0].className+=' alternativeTheme'; \\ Note the SPACE in there!
      }
      

      This would add “alternativeTheme” to the body of the document, and you would have a section in your css dedicated to it. For example:

      body {
          background-color:blue;
      }
      body.alternativeTheme {
          background-color:red;
      }
      

      Now, Im SURE there are all sorts of other ways to do this that are better or whatever. I’m sure somebody will post more about it. But this should get your wheels spinning as to what type of options are out there with a little bit of CSS and JS.

      (This type of alternate theme could be done in a separate stylesheet. Using Sass would make it easier using nesting. If you aren’t familiar with Sass, check out the website at http://sass-lang.com/guide.

      Cheers!

  16. User Avatar
    Vman
    Permalink to comment#

    to access array from right to left:

    secondLevelLocation[secondLevelLocation.length-1]

  17. User Avatar
    WebMechanix
    Permalink to comment#

    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!

    • User Avatar
      Andrei-Robert Rusu
      Permalink to comment#

      Keep it simple stupid, lol.

      window.location.protocol + "//" + (window.location.host + "/" + window.location.pathname).replace('//', '/');
      
  18. User Avatar
    Ryan
    Permalink to comment#

    Essentially what I’m trying to do is a video setup, where my url would be
    [video src="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?

    
    var pathArray = window.location.pathname.split('=');
    
    var VideoFile = pathArray[1];
    
    
  19. User Avatar
    Gleb Denisov
    Permalink to comment#

    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)

  20. User Avatar
    william malo

    you can just use “location” ex.

    var newURL = location

  21. User Avatar
    Juliawan

    Thanks for the Information :D

  22. User Avatar
    Sandra

    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

    • User Avatar
      Gerald

      window.top.location.replace(“http://newdomain.com/”+window.location.host.split(‘.’)[0]);

      Hope Sandra will find a solution with this.

  23. User Avatar
    Mannan
    Permalink to comment#

    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?

  24. User Avatar
    balics
    Permalink to comment#

    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

  25. User Avatar
    aldotcom
    Permalink to comment#

    Hey pal, thank you for your posting. I need it for my JS project.
    Best regards,
    Anton

  26. User Avatar
    StephaneAG
    Permalink to comment#

    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:

    
    var newURL = window.location.protocol + '//' + window.location.host + window.location.pathname
    console.log('New url content  : '  + newURL );
    

    or even (if I am right in the order) :

    
    var newURL = window.location.protocol + '//' + window.location.host + window.location.pathname +  window.location.search + window.location.hash
    console.log('New url content  : '  + newURL );
    

    For the short-hand versions:
    After testing, they seems to work cross-browsers (..)

    
    window.location & document.URL
    

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

  27. User Avatar
    Syedur
    Permalink to comment#

    This much helpful for me. Thanks

  28. User Avatar
    Wills Bithrey
    Permalink to comment#

    Really useful quick reference Chris, thanks!

    Would it be worth adding window.location.search and window.location.port in there too :)?

  29. User Avatar
    WebGyver
    Permalink to comment#

    Might want to add a < or some kind of operator into that for loop:

    for ( i = 0; i pathArray.length; i++ ) {

    fwiw

  30. User Avatar
    Albert Renshaw
    Permalink to comment#

    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)

    • User Avatar
      Albert Renshaw
      Permalink to comment#

      Some comments above could be added to! I completely forgot about window.location.port! Nice!

  31. User Avatar
    ddlab
    Permalink to comment#

    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');

    • User Avatar
      ddlab
      Permalink to comment#

      sorry, mixed syntax, better like this

      var newurl = window.location.protocol.replace(/\:/g,'') + '://' + window.location.host + window.location.pathname.replace(/html/g,'php');

  32. User Avatar
    Mickours
    Permalink to comment#

    You forgot to the comparison term in the for loop…
    Thanks for your post anyway ^^

  33. User Avatar
    Loghman
    Permalink to comment#

    Love U Chris…

  34. User Avatar
    Tommy
    Permalink to comment#

    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

    • User Avatar
      NaBr0
      Permalink to comment#


      var pathArray = window.location.pathname.split( '/' );
      //["", "patents", "US20120211565"]

      pathArray[2];
      //US20120211565

    • User Avatar
      Milo LaMar
      Permalink to comment#

      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.

      
      window.location.pathname.split('/').pop();
      
      

      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

      
      var myURL = 'http://www.google.com/patents/US20120211565////////';
      var myURLArray = myURL.split('/');
      var lastChunk = '';
      while (myURLArray.length > 0 && lastChunk == '') {
        //put the last element of myURLArray into the variable lastChunk
        lastChunk = myURLArray.pop();
      }
      console.log(lastChunk); // US20120211565
      
      
  35. User Avatar
    Tommy
    Permalink to comment#

    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!

  36. User Avatar
    milo
    Permalink to comment#

    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

    • User Avatar
      Tommy
      Permalink to comment#

      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!

  37. User Avatar
    John Doe
    Permalink to comment#

    Hey Chris Coyier, Ben Chapman is wrong, or browsers have changed since then. There shouldn’t be an added colon.

  38. User Avatar
    Ernesto
    Permalink to comment#

    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=%5Bcsid%5D and the [csid] would be the variable that changes depending on where the traffic came from

    such as http://mywebsite.com/?c1=%5Bcsid%5D 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.

    • User Avatar
      Ernesto
      Permalink to comment#

      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

  39. User Avatar
    macherif
    Permalink to comment#

    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 + "/";
    }

    }

  40. User Avatar
    PellePenna

    Maybe something like this can be handy ….
    getUrlBase = function () {
    return location.protocol.split(‘:’)[0] + ‘://’ + location.host + ‘/’;
    }
    getUrlPart = function (idx) {
    var parts = location.href.substring(getUrlBase().length).split(‘/’);
    return (parts.length >= idx && idx > 0) ? parts[idx – 1] : ”;
    }
    getUrlBase(); // will give you “http://css-tricks.com/” on below url
    getUrlPart(2); // will give you “javascript” on below url
    url: “http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/”

  41. User Avatar
    Mohamed
    Permalink to comment#

    I use the following function to get the url parameters in an array form:

    function getUrlVars() {
        var vars = [], hash;
        var decodedUrl = decodeURIComponent(window.location.href);
        var hashes = decodedUrl.slice(decodedUrl.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
    

    Dot notation

    getUrlVars().actions
    

    Square bracket notation

    getUrlVars()['actions']
    

    Thanks,
    Mohamed

    • User Avatar
      Himansu
      Permalink to comment#

      Yup, it works perfectly for me.

      Thanks,
      Himansu

    • User Avatar
      Kevin
      Permalink to comment#

      I was able to use your code and was able to pull the following:

      document.write(“Names of incoming vars: ” +vars+ ” “);
      document.write(“Name of first incoming var: ” +vars[0]+ ” “);

      I am now attempting to pull the unique value found in each incoming variable name. Suggestions welcome.

      All the best,

      Kevin

  42. User Avatar
    Charles

    In my case I used like that for extract last name with out .html.

    Great Thanks for posting……….

  43. User Avatar
    Charles

    var pathArray = window.location.pathname.split( ‘/’ );

    alert(pathArray[pathArray.length-1].replace(/.html/g,”));

  44. User Avatar
    Noah
    Permalink to comment#

    The pathname worked awesome when I needed to find the name of the file I was viewing (index.htm) when it wasn’t in the url.

  45. User Avatar
    Ashutosh Kumar
    Permalink to comment#

    how we remove the spaces from url plzz suggest..thanks in advance

  46. User Avatar
    Harish
    Permalink to comment#

    How to get URL Name i mean suppose if url is https://www.google.com
    I need url name is (GOOGLE).Please any one help in this

  47. User Avatar
    PellePenna
    Permalink to comment#

    Harish, I do it like this when needed:

    function endsWith(str, suffix) {
        return str.indexOf(suffix, str.length - suffix.length) !== -1;
    }
    var urlDomainName;
    var hostArray = window.location.host.split( '.' );
    if (hostArray.length < 3) {
        urlDomainName = hostArray[0];
    } else {
        //now it gets more complicated, because a host 
        //can look like this:
        //  - www.domainname.com
        //  - www.sub.domainname.com
        //  - domainname.uk.com
        //  - www.domainname.uk.com
        //  - www.sub.domainname.uk.com
        //which means that you need to put all top 
        //domains in an array and loop through
        //them, or use a regex
    
        var host = window.location.host;
        var topdomains = ["uk.com","au.com",...,"net","com",...]
        var length = topdomains.length;
        for (var i = 0; i < length; i++) {
            if (endsWith(host,topdomains[i])) {
                urlDomainName = topdomains[i];
                break;
            }
        }
    }
    
    • User Avatar
      PellePenna
      Permalink to comment#

      Ooops … something went wrong on host variants … obviously a “http://” were added to hosts starting with “www”

  48. User Avatar
    PellePenna
    Permalink to comment#

    And of course this is how the for-loop should be:

    for (var i = 0; i < length; i++) {
        if (endsWith(host,topdomains[i])) {
            var topArray = topdomains[i].Split( '.' );
            urlDomainName = hostArray[hostArray.length - topArray.length - 1];
            break;
        }
    }
    
  49. User Avatar
    Harish
    Permalink to comment#

    Hi Pelle,
    Thanks for ur response But we cant put all domains in array why becoz now a days somany domains are avaialable.I mean suppose 1000 domains are there means we cant put thousand in array right.
    Thanks,
    Harish

    • User Avatar
      PellePenna
      Permalink to comment#

      Hi Harish,

      There aren’t 1000’s of top level domains, there are about 300 and this is the only way to detect the domain name in the way you asked for.

      After a quick googling I found http://publicsuffix.org/, where you will find a list of them and more info how to use the list.

      You will also find libraries you can use to parse and find the top level domain, but it’s still a list that your host name needs to be compared against.

  50. User Avatar
    Avi
    Permalink to comment#

    Thanks for putting this information. pathname was what I was looking for.

  51. User Avatar
    Milder Lisondra
    Permalink to comment#

    Simply but SOOOOO useful. Thank you for posting.

  52. User Avatar
    Bee
    Permalink to comment#

    I need HTML Help: this is a simple search box but i need it to do this

    Heres the original url:
    site.com

    Heres the url when i type : test1 in the search box:
    site.com/?q=test1

    Heres what i NEED it to look like when you type : test1 into the search box:
    site.com/test1.php

    cant figure out how to use the #replace# feature

    `<br>                   
    <td class="pastissues" width="160">
    <form action="http://yolasite.com" method="get">
    <b>Search for:</b>
    <div align="center">
    <input size="10" name="q" type="text" style="font-family:arial,helvetica,sans-serif; font-weight:bold; font-size:12px;">&nbsp;&nbsp;<input type="submit" value=" Go ">
    </div>
    <br>`
    
    • User Avatar
      PellePenna
      Permalink to comment#

      You add a name to the form and an onsubmit event, where you catch and do your stuff.

      <br>                   
      <td class="pastissues" width="160">
      <form action="http://site.com/" method="get" name="frmsearch" onsubmit="do_frmsearch()">
      <b>Search for:</b>
      <div align="center">
      <input size="10" name="q" type="text" style="font-family:arial,helvetica,sans-serif; font-weight:bold; font-size:12px;">&nbsp;&nbsp;<input type="submit" value=" Go ">
      </div>
      
      <script>
      function do_frmsearch(e) {
        //prevent form submit
        e = e || window.event;
        if (e.preventDefault)
          e.preventDefault();
        else
          e.returnValue = false;
        //you want to get rid of "?q=test", use location.href
        location.href = document.forms["frmsearch"].action + document.forms["frmsearch"]["q"].value + '.php';  
      }
      </script>
      <br>
      

      If you still want to submit the form, change form method from “get” to “post” to get rid of “?q=test” in the url and use this script instead of above

      <script>
      function do_frmsearch(e) {
        document.forms["frmsearch"].action += document.forms["frmsearch"]["q"].value + '.php';
      }
      </script>
      
  53. User Avatar
    Bee
    Permalink to comment#

    thanks :) after hours-got it working

  54. User Avatar
    Raman
    Permalink to comment#

    I have a requirement as follows: we have two application one in English and other in chinese.
    Ex: home pages: ‘http://mysite.com/en/home/index.html’
    http://mysite.com/ch/home/index.html
    Press release pages: ‘http://mysite.com/en/home/pressreleases/index.html’
    ‘http://mysite.com/ch/home/pressreleases/index.html’

    Now when i select EN(language option on header) on chinese press page( ‘http://mysite.com/ch/home/pressreleases/index.html’) this link take me to English home page. i should make this to redirect EN pressrelease page directly.
    Am trying this with below solution. sample logic:
    function chooseLang()
    {
    // http://mysite.com/ch/home/pressreleases/index.html

    var currURl= window.location.href;
    var urlArray= window.location.pathname.split( ‘/’ );
    var isCHorEN = urlArray[0];
    if (isCHorEN ==’ch’)
    {
    newUrl=…
    }
    else if(isCHorEN ==’en’)
    {
    newUrl=..
    }

    }

    Could someone provide code snippet on this. Thanks in advance.

    • User Avatar
      milo
      Permalink to comment#

      window.location.pathname includes the first forward slash so “/ch/home/pressreleases/index.html” in your example so you’ll want index at 1, not 0 to get “ch” or “en”

      A better solution for your problem might just be to change location with a String.replace() call https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

      so window.location.href=window.location.href.replace(“/ch/”, “/en/”) if they choose english from chinese,
      window.location.href=window.location.href.replace(“/en/”, “/ch/”) if they choose chinese from english,
      and nothing if they choose the same language they are currently on.

  55. User Avatar
    PellePenna
    Permalink to comment#

    Merry Christmas every one … :)

    function chooseLang(e) {
        var pathName = window.location.pathname;
        //trim any leading slash
        var pathArray = (pathName.substring(0,1) == '/') ? 
                         pathName.substring(1).split('/') : 
                         pathName.split('/');
        //toggle lang
        if (pathArray[0] == 'cn')
            pathArray[0] = 'en';
        else
            pathArray[0] = 'cn';
        //load page
        window.location.href = window.location.protocol + '//' + 
                               window.location.host + '/' + 
                               pathArray.join('/');
        //you might need to cancel default event as well
        e = e || window.event;
        if (e.stopPropagation) e.stopPropagation();
        if (e.preventDefault) e.preventDefault();
        e.returnValue = false;
        return false;
    }
    
  56. User Avatar
    Mohamed Ali Bouhoum
    Permalink to comment#

    Hello;
    I was looking around and probably I wasn’t looking right …
    Anyway I’m trying something (even it’s been already made) but used it with PHP (sending par with urls …) so got something like this index.php?size=500×500 , but i’m wondering if there’s any JS way to make it index.php/500×500 only and even if you change the par in the link can work …

    Thank you for help :)

  57. User Avatar
    od3n
    Permalink to comment#

    simply but so useful. thank you for posting

  58. User Avatar
    hugolpz
    Permalink to comment#

    You may add the file name trick:
    location.href.split(“/”).slice(-1)
    This is cool to customize nav box’s link to current page by adding a class with enlighting styles.
    $(‘.menu a’).each(function() {
    if ($(this).attr(‘href’) == location.href.split(“/”).slice(-1)){ $(this).addClass(‘curent_page’); }
    });

  59. User Avatar
    But alas

    Nitpick:
    window.location.protocol = “http” (on line 3 in the article) is incorrect, you get the colon too: window.location.protocol = “http:” (this is as of Chrome 34 and Firefox 29).

  60. User Avatar
    vilas

    Sir, i want dynamically get URL of all open browser & write the URL in text files.. so plz provide the script or source code in jsp…
    i hope reply….

  61. User Avatar
    Fawad Akhtar

    that is exactly i was searching for, you are awesome “Chris Coyier”

  62. User Avatar
    Siva krishna

    I wanted to retrieve the url from current working browser in my system by using java program.So what i have to do suggest me….plz

  63. User Avatar
    jayism
    Permalink to comment#

    I’ve been searching for a way to add certain domains to a sites header (eg ->
    `
    var varurl = “http://linkguard.biz/secure.php?link=”;
    var shortem = [‘google.com’, ‘putlocker.com’, ‘netload.in’, ‘uploaded.net’, ‘rapidshare.com’, ‘yoursite.com’, ‘yoursite.com’, ‘yoursite.com’, ‘yahoo.com’, ‘yoursite.com’, ‘yoursite.com’, ‘yoursite.com’, ‘yoursite.com’, ];

    `

    So every domain you enter in here (I borrowed this from a site that uses this method, however after days of trial and error & resarch I’m at my wits end (JS & PHP are not my strong suits – this will be uploaded to a WordPress installations directory hopefully as a get.php file that acts like-:
    a page with a button on it ‘Continue to Link’ so this can be used as a way for users to have an interim page inbetween for affiliate banners/advertising.

    It’s basically a Redirection Script, with an interim page inbetween. I wanted to put a captcha.php?link=hdhGHSOOEDjkkOOPSPSPnnAwKLd type situation in there, that the captcha had to be filled before being directed to the get.php page though this seem like alot of work for whoever is willing to give me the get.php code needed (and another page perhaps?) for this to work!

    This is from a site called Linkguard, however it was recently just apart of a WordPress Site & worked in-house until the Author decided to move it off to it’s own site to let other’s use it – however this is not my goal. Aslong as it works on domain(s) I can put the code into manually (as above – or similar) & can easily upload a .php file to wordpress, or any site for that matter where links are directed through this if they sport the domain name required.

    WOW! What a long post, it came off way more complex in writing it out, then it looks from the source codes I could make heads or tales of…

    I have searched google numerous times and there is nothing quiet like this, that I can find anyhow. I have stumbled across something similar I could have worked with years ago, but it is now lost in the interwebs somewhere – and CSS-Tricks.com was high up on the keywords for this, and it looks like there are Codes Above ^^ that are getting pretty darn close.

    Cheers to anyone that has the patience to help me out here. And well anyone that has read this far LOL.

    MUCH APPRECIATED!
    @jaycameron

    • User Avatar
      jayism
      Permalink to comment#

      Oops I ruined the code block, I have this trouble on forrst too. Argh!

      script language="javascript" type="text/javascript"
      var varurl = "http://linkguard.biz/secure.php?link=";
      var shortem = ['google.com', 'putlocker.com', 'netload.in', 'uploaded.net', 'rapidshare.com',       'yoursite.com', 'yoursite.com', 'yoursite.com', 'yahoo.com', 'yoursite.com', 'yoursite.com',    'yoursite.com', 'yoursite.com', ];
      /script
      script type="text/javascript" src="http://scriptsandip.googlecode.com/files/full-page-script.js" /script
      

      I could not put the on each side of the JS script tags for some reason…

      Thanks Again Guys & Chris!

  64. User Avatar
    melody
    Permalink to comment#

    how do i detect if it’s not on a subpage? shouldn’t something like
    if (window.location.pathname == false) work? i want to make code that detects if you are on the home page, then sends you to a subpage, but if you are on a subpage, it won’t redirect.

    • User Avatar
      PellePenna
      Permalink to comment#

      It should be something like:

      if  (window.location.pathname == 'your_home_page_path') {
          //send to some subpage
          window.location.href = 'sub_page_path';
      }
      
    • User Avatar
      melody
      Permalink to comment#

      yeah i got it working! the problem was, i couldn’t figure out what “pathname” was returning when you weren’t on a subpage. (my homepage is not on a subpage) apparently it returns “/” so i did:

      var pathname = window.location.pathname;
      if (pathname == '/')
      {
      window.location.pathname = "/tagged/p";
      }
      

      and now it’s working 100%. now on to the real problem: making it redirect to a different subpage at a different time of day (but again only from the homepage)

    • User Avatar
      PellePenna
      Permalink to comment#

      Maybe something like this:

      if  (window.location.pathname == 'your_home_page_path') {
          var d = new Date();
          var h = d.getHours();
          switch (h) {
              case (>=6 && <10):
                  window.location.href = 'sub_page_morning';
                  break;
              case (>=10 && <14):
                  window.location.href = 'sub_page_lunch';
                  break;
              case (>=14 && <18):
                  window.location.href = 'sub_page_afternoon';
                  break;
              case (>=18 && <22):
                  window.location.href = 'sub_page_evening';
                  break;
              default:
                  window.location.href = 'sub_page_sleeping';
          }
      }
      
    • User Avatar
      melody
      Permalink to comment#

      here’s what i’ve settled on, it isn’t doing a redirect loop so im assuming it’s working. i’ll wait until 8 pm since i dont want to change it anymore and tell you if it worked

      var d = new Date() 
      var time = d.getHours()
      var pathname = window.location.pathname;
      if (pathname == '/' && 6 <= time < 20) 
      {
          window.location.pathname = "/tagged/p"
      }
      else if (pathname == "/")
      {
          window.location.pathname= "/tagged/g"
      }
      
  65. User Avatar
    Lioooo
    Permalink to comment#

    Hi Friends .. need your help in this please :)
    I have a page : http://192.168.2.2:4444/pages/hello.html
    if visited , then redirected to the following page
    http://192.168.2.2:5555/cgi-bin/hello.cgi?mode=welcome
    Thanks !

  66. User Avatar
    Yazin
    Permalink to comment#

    I ended up using the following, which works for full URLs, as well as relative ones:

      base_path_parts = thisScript.attr("src").split('/');
      base_path = "";
      for(i=0;i<base_path_parts.length-1;i++) {
        // The following if fixes the case where we have consecutive '/'
        // like in http://google.com/home/
        if(base_path_parts[i]!=''){
          base_path+= base_path_parts[i] + "/";
        } else {
          base_path+= "/";
        }
      }
    
  67. User Avatar
    Mike
    Permalink to comment#

    Use window.location.hostname instead of window.location.host

    eg. example.com:8888

    window.location.hostname = example.com
    window.location.host = example.com:8888

  68. User Avatar
    Gvanto
    Permalink to comment#

    Hey thanks for a great post. I have a requirement to extract the ‘&country’ parameter from my URL and putting it at the start of the query string – any ideas?

    • User Avatar
      PellePenna
      Permalink to comment#
      // Split the pathname
      var params = window.location.search.split('&');
      
      // Remove first ? if any
      params[0] = params[0].replace('?', '');
      
      // New pathname
      var newsearchstring = '';
      
      // Loop params and look for country
      for(i=0;i<params.length-1;i++) {
          var param = params[i].split('=');
          if (param == 'country') {
              // found it, add it first
              newsearchstring = (newsearchstring.length > 0 ? '&' : '?') + params[i] + newsearchstring;
          } else {
              // found other, add it at end
              newsearchstring += (newsearchstring.length > 0 ? '&' : '?') + params[i];
          }
      }
      
      // Now you got the "newsearchstring" with country first
      
    • User Avatar
      PellePenna
      Permalink to comment#

      Oooops .. made some mistakes in previous comment:

      // Split the search string
      var params = window.location.search.split('&');
      
      // Remove first ? if any
      params[0] = params[0].replace('?', '');
      
      // New search string
      var newsearchstring = '';
      
      // Loop params and look for country
      for(i=0;i<params.length-1;i++) {
          var param = params[i].split('=');
          if (param == 'country') {
              // found it, add it first
              newsearchstring = '?' + params[i] + newsearchstring;
          } else {
              // found other, add it at end
              newsearchstring += (newsearchstring.length > 0 ? '&' : '') + params[i];
          }
      }
      
      // Now you got the "newsearchstring" with country first
      
      
  69. User Avatar
    Ruby
    Permalink to comment#

    how to get url when system ideal

  70. User Avatar
    Milind K.
    Permalink to comment#

    simply but so useful. thank you for posting

  71. User Avatar
    Garvan
    Permalink to comment#

    Are there any drawbacks for using window.location.href to get the full location?

  72. User Avatar
    Nived Kannada
    Permalink to comment#

    Its nice ! But I wanna know how to get the url part after a “=” equal icon !

    I want to redirect to the url(I’m trying to do it) after the equal to icon ! :-D

    Please tell me the answer for this question !

  73. User Avatar
    Per Kristian
    Permalink to comment#

    If you are looking to get the root URL (http://www.example.com/) from any URL, this one line of code will do it for you:

    return window.location.origin?window.location.origin+'/':window.location.protocol+'/'+window.location.host+'/';
    

    If you are looking to get the base URL (http://www.example.com/something/) from any URL, use these two lines of code:

    var re = new RegExp(/^.*\//);
    return re.exec(window.location.href);
    

    Further explanation and complete functions to copy/paste here: Javascript: Get base URL or root URL

  74. User Avatar
    Setiawan
    Permalink to comment#

    I have some problem.

    for example, i have this link :
    http://example.com/index.html?id=lunch

    I want to take “lunch” on my script using “if function”. How I can do it?

    I mean, the main script like this.
    If id=lunch, then do write text on page “enjoy your lunch!”.

    help me please…

    • User Avatar
      Dahico
      Permalink to comment#

      Not sure but check split in javascript. Also c# has split function too. İf u are using mvc you can just assign variable like id from route config

  75. User Avatar
    hamed
    Permalink to comment#

    if my url is http://www.domain.com and i want to get only domain.com
    without using split

  76. User Avatar
    Herman Nz
    Permalink to comment#

    Simple but that’s what I’m looking for. thanks a lot.

  77. User Avatar
    Roland
    Permalink to comment#

    Just wanted to say that i like your page a lot. I`m learning CSS and Javascript and you page will come in handy. Thank you.

  78. User Avatar
    porkodi
    Permalink to comment#

    frnds, i need a feature extraction of a particular url. i want to find a rank of the url if i gave http://facebook.com means it should go to http://www.alexa.com and the rank of the url will be display in the webpage i want to save that rank value into mysql database.pls help me to get this code

  79. User Avatar
    Nived Kannada
    Permalink to comment#

    Hello. This is good and I got a doubt. suppose we have a url www.google.com/?go=
    And I want to get the part after that ?go= thing. And I want to redirect to the url after that go= ! Can anybody tell me how to do this?
    All I wanna do is that just redirect to the url after go= !

  80. User Avatar
    KCOtzen

    Very useful! thanks!

  81. User Avatar
    Vitor
    Permalink to comment#

    Saved me today. Thank you!!!

  82. User Avatar
    Nguyen Duc Tai

    var url = window.location.host + window.location.pathname;
    window.location.href = “http://”+url;

  83. User Avatar
    Dahico
    Permalink to comment#

    Dude you are awesome.. I’ve been searching and searching for that and all the websites were useless at this subject even stackoverflow. You literally saved the day for me.

    Thank you

  84. User Avatar
    priyadharshini
    Permalink to comment#

    send the code to get the url while clicking the button

  85. User Avatar
    Daenarii Shiginima
    Permalink to comment#

    I think some browsers (probably old ones) might render the script invalid.

    I recommend replacing this with

    var newURL = window.location.protocol + "/" + "/" + window.location.host + "/" + window.location.pathname;
    

    because my phone thinks of the “//” as a comment.

  86. User Avatar
    gokhan
    Permalink to comment#

    I am looking for that i want to get all urls into array or txt from google search with using javascript.My code does the search part but i also need urls. Does anybody help me ? Thanks in advance

  87. User Avatar
    chafiq
    Permalink to comment#

    I am using window.location.href.split(“=”)[1] to capture query strings values and send through a form. My url is like this example.com?source=qs1

    My issue is google adwords appends a gclid value that gets parsed as well, so I get source=qs1&gclid

    Any way for me to get rid of anything that comes after the &?

    Thanks in advance.

  88. User Avatar
    Divo
    Permalink to comment#

    Thank you so much for these tricks. Very useful to me.

  89. User Avatar
    sajid
    Permalink to comment#

    hi admin how are you can you tell me which method to create script like

    websitename.com/link.php

    if am use any link from our website its showing like

    websitename.com/link.php?url=md5 and open external link like indishare or many of other external links generater sites please help me ?

  90. User Avatar
    Samsul Arif
    Permalink to comment#

    simply use window.location.href to get full path of url :D

  91. User Avatar
    Luuk Lamers
    Permalink to comment#

    We’re now living in 2016 and I really think the stitching in the last example should be replaced by:

    pathArray.join("/")
    

    unless you want to leave the n first or n last parts out:

    var first = 1; // the second element
    var last = -2; // the second to last element
    pathArray.slice(first, last).join("/");
    

    or if you only want the n last elements:

    var num = -4;
    pathArray.slice(num).join("/");
    
    • User Avatar
      Luuk Lamers
      Permalink to comment#
      var last = -2; // the third to last element
      

      Typo: this should be third to last element ofcourse.

  92. User Avatar
    Oleg Derecha
    Permalink to comment#

    Thant’s it! Thank you!

  93. User Avatar
    Vik Ramanujam
    Permalink to comment#

    I’ve been looking around and find this to be the best possible way to get the whole url (proto://hostname:port) in the shortest bit of code:

    if (!window.location.origin) {
      window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
    }
    
  94. User Avatar
    Sean
    Permalink to comment#

    In your bullet points at the top—
    window.location.pathname = "example/index.html"
    —should be—
    window.location.pathname = "/example/index.html"

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag