Last segment of URL












175















How do I get the last segment of a url? I have the following script which displays the full url of the anchor tag clicked:



$(".tag_name_goes_here").live('click', function(event)
{
event.preventDefault();
alert($(this).attr("href"));
});


If the url is



http://mywebsite/folder/file


how do I only get it to display the "file" part of the url in the alert box?










share|improve this question

























  • Below is my working java script solution.Hope it helps. stackoverflow.com/a/38370175/610951

    – Ravi
    Jul 14 '16 at 9:19
















175















How do I get the last segment of a url? I have the following script which displays the full url of the anchor tag clicked:



$(".tag_name_goes_here").live('click', function(event)
{
event.preventDefault();
alert($(this).attr("href"));
});


If the url is



http://mywebsite/folder/file


how do I only get it to display the "file" part of the url in the alert box?










share|improve this question

























  • Below is my working java script solution.Hope it helps. stackoverflow.com/a/38370175/610951

    – Ravi
    Jul 14 '16 at 9:19














175












175








175


31






How do I get the last segment of a url? I have the following script which displays the full url of the anchor tag clicked:



$(".tag_name_goes_here").live('click', function(event)
{
event.preventDefault();
alert($(this).attr("href"));
});


If the url is



http://mywebsite/folder/file


how do I only get it to display the "file" part of the url in the alert box?










share|improve this question
















How do I get the last segment of a url? I have the following script which displays the full url of the anchor tag clicked:



$(".tag_name_goes_here").live('click', function(event)
{
event.preventDefault();
alert($(this).attr("href"));
});


If the url is



http://mywebsite/folder/file


how do I only get it to display the "file" part of the url in the alert box?







javascript jquery






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 21 '11 at 11:25









Felix Kling

546k126849909




546k126849909










asked Jan 21 '11 at 11:11









oshirowanenoshirowanen

3,07071162305




3,07071162305













  • Below is my working java script solution.Hope it helps. stackoverflow.com/a/38370175/610951

    – Ravi
    Jul 14 '16 at 9:19



















  • Below is my working java script solution.Hope it helps. stackoverflow.com/a/38370175/610951

    – Ravi
    Jul 14 '16 at 9:19

















Below is my working java script solution.Hope it helps. stackoverflow.com/a/38370175/610951

– Ravi
Jul 14 '16 at 9:19





Below is my working java script solution.Hope it helps. stackoverflow.com/a/38370175/610951

– Ravi
Jul 14 '16 at 9:19












22 Answers
22






active

oldest

votes


















278














You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substr() function to return the substring starting from that location:



window.alert(this.href.substr(this.href.lastIndexOf('/') + 1));


That way, you'll avoid creating an array containing all your URL segments, as split() does.






share|improve this answer





















  • 2





    @oshirowanen, no, but it will create an array element from each URL segment. Since you're only interested in the last segment, it might be wasteful to allocate many array elements that you'll never use.

    – Frédéric Hamidi
    Jan 21 '11 at 11:23






  • 7





    But if the url was become like admin/store/tour/-1/ so it's will be '' string?

    – Set Kyar Wa Lar
    Aug 20 '14 at 8:39








  • 1





    @Set, nicer maybe, slower surely.

    – Frédéric Hamidi
    Aug 20 '14 at 8:58






  • 1





    For future readers, do not rely on the href attribute, it is unresolved and can contain things like ../ meaning up one directory. Use the native property instead, like this.href.

    – Walf
    Aug 4 '16 at 0:53








  • 3





    Attn: @Set Kyar Wa Lar Aug and @Sнаđошƒаӽ Solution for url that contains a / at the end: var url = window.location.href.replace(//$/, ''); /* remove optional end / */ var lastSeg = url.substr(url.lastIndexOf('/') + 1);

    – Ross
    Nov 2 '16 at 3:18





















115

















var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash

console.log(lastSegment);








share|improve this answer


























  • Can you explain me how it work's? as per my knowledge .pop() used for remove last element of a array. but is here it showed last element of my url!!

    – Inspire Shahin
    Dec 15 '15 at 7:33






  • 1





    Split will convert your url into an array taking each section of the url delimited by '/'. Hence the last segment is the last element of both the url and the subsequently created array.

    – stephen
    Feb 22 '16 at 23:46






  • 9





    This won't work if the url ends with a "/" i.e. http://mywebsite/folder/file/

    – Peter Ludlow
    Feb 25 '16 at 4:40





















36














window.location.pathname.split("/").pop()





share|improve this answer
























  • simple and easy. Thanks.

    – krezaeim
    Sep 24 '18 at 18:01











  • Perfect and tidy, great

    – Babak Habibi
    Oct 11 '18 at 12:29



















23














Just another solution with regex.



var href = location.href;
console.log(href.match(/([^/]*)/*$/)[1]);





share|improve this answer



















  • 2





    this works great if URL ends with /

    – Shoaib Iqbal
    Nov 14 '16 at 6:00



















16














Javascript has the function split associated to string object that can help you:



var url = "http://mywebsite/folder/file";
var array = url.split('/');

var lastsegment = array[array.length-1];





share|improve this answer































    9














    Or you could use a regular expression:



    alert(href.replace(/.*//, ''));





    share|improve this answer































      8














      var urlChunks = 'mywebsite/folder/file'.split('/');
      alert(urlChunks[urlChunks.length - 1]);





      share|improve this answer































        5














        I know, it is too late, but for others:
        I highly recommended use PURL jquery plugin. Motivation for PURL is that url can be segmented by '#' too (example: angular.js links), i.e. url could looks like



            http://test.com/#/about/us/


        or



            http://test.com/#sky=blue&grass=green


        And with PURL you can easy decide (segment/fsegment) which segment you want to get.



        For "classic" last segment you could write:



            var url = $.url('http://test.com/dir/index.html?key=value');
        var lastSegment = url.segment().pop(); // index.html





        share|improve this answer































          4














          Building on Frédéric's answer using only javascript:



          var url = document.URL

          window.alert(url.substr(url.lastIndexOf('/') + 1));





          share|improve this answer































            3














            Also,



            var url = $(this).attr("href");
            var part = url.substring(url.lastIndexOf('/') + 1);





            share|improve this answer































              3














              If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).



              url.split('/').filter(function (s) { return !!s }).pop()





              share|improve this answer































                3














                // Store original location in loc like: http://test.com/one/ (ending slash)
                var loc = location.href;
                // If the last char is a slash trim it, otherwise return the original loc
                loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
                var targetValue = loc.substr(loc.lastIndexOf('/') + 1);


                targetValue = one



                If your url looks like:




                http://test.com/one/




                or




                http://test.com/one




                or




                http://test.com/one/index.htm




                Then loc ends up looking like:
                http://test.com/one



                Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.



                var targetValue = loc.substr(loc.lastIndexOf('/') + 1);





                share|improve this answer


























                • I probably miss something, but with "test.com/one" loc ends up looking like : "test.com". I think it should be like : if( loc.lastIndexOf('/') == (loc.length -1) ){ loc = loc.substr(0,loc.length-1) }else{ var isFile = loc.substr(loc.lastIndexOf('/'),loc.length).indexOf('.') != -1; if(isFile) loc = loc.substr(0,loc.lastIndexOf('/')); }

                  – Allan Raquin
                  Aug 3 '16 at 13:53











                • Fails if slash in search or hash.

                  – Walf
                  Aug 4 '16 at 0:42



















                3














                window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));


                Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.



                If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:



                window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);





                share|improve this answer


























                • Also want to add that pathname strips query parameters, but href does not.

                  – Max Heiber
                  Aug 3 '16 at 15:33



















                3














                The other answers may work if the path is simple, consisting only of simple path elements. But when it contains query params as well, they break.



                Better use URL object for this instead to get a more robust solution. It is a parsed interpretation of the present URL:



                Input: const href = 'https://stackoverflow.com/boo?q=foo&s=bar'



                const last = new URL(href).pathname.split('/').pop();
                console.log(last);


                Output: 'boo'






                share|improve this answer

































                  2














                  var pathname = window.location.pathname; // Returns path only
                  var url = window.location.href; // Returns full URL


                  Copied from this answer






                  share|improve this answer

































                    2














                    To get the last segment of your current window:



                    window.location.href.substr(window.location.href.lastIndexOf('/') +1)






                    share|improve this answer































                      1














                      Updated raddevus answer :



                      var loc = window.location.href;
                      loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
                      var targetValue = loc.substr(loc.lastIndexOf('/') + 1);


                      Prints last path of url as string :



                      test.com/path-name = path-name

                      test.com/path-name/ = path-name





                      share|improve this answer

































                        1














                        Returns the last segment, regardless of trailing slashes:






                        var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();

                        console.log(val);








                        share|improve this answer

































                          0














                          I believe it's safer to remove the tail slash('/') before doing substring. Because I got an empty string in my scenario.



                          window.alert((window.location.pathname).replace(//$/, "").substr((window.location.pathname.replace(//$/, "")).lastIndexOf('/') + 1));





                          share|improve this answer































                            0














                            I am using regex and split:



                            var last_path = location.href.match(/./(.[w])/)[1].split("#")[0].split("?")[0]



                            In the end it will ignore # ? & / ending urls, which happens a lot. Example:



                            https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm



                            https://cardsrealm.com/profile/cardsRealm#hello -> Returns cardsRealm



                            https://cardsrealm.com/profile/cardsRealm?hello -> Returns cardsRealm



                            https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm






                            share|improve this answer

































                              0














                              you can first remove if there is / at the end and then get last part of url



                              let locationLastPart = window.location.pathname
                              if (locationLastPart.substring(locationLastPart.length-1) == "/") {
                              locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
                              }
                              locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);





                              share|improve this answer































                                0














                                I don't really know if regex is the right way to solve this issue as it can really affect efficiency of your code, but the below regex will help you fetch the last segment and it will still give you the last segment even if the URL is followed by an empty /. The regex that I came up with is:



                                [^/]+[/]?$





                                share|improve this answer























                                  Your Answer






                                  StackExchange.ifUsing("editor", function () {
                                  StackExchange.using("externalEditor", function () {
                                  StackExchange.using("snippets", function () {
                                  StackExchange.snippets.init();
                                  });
                                  });
                                  }, "code-snippets");

                                  StackExchange.ready(function() {
                                  var channelOptions = {
                                  tags: "".split(" "),
                                  id: "1"
                                  };
                                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                                  StackExchange.using("externalEditor", function() {
                                  // Have to fire editor after snippets, if snippets enabled
                                  if (StackExchange.settings.snippets.snippetsEnabled) {
                                  StackExchange.using("snippets", function() {
                                  createEditor();
                                  });
                                  }
                                  else {
                                  createEditor();
                                  }
                                  });

                                  function createEditor() {
                                  StackExchange.prepareEditor({
                                  heartbeatType: 'answer',
                                  autoActivateHeartbeat: false,
                                  convertImagesToLinks: true,
                                  noModals: true,
                                  showLowRepImageUploadWarning: true,
                                  reputationToPostImages: 10,
                                  bindNavPrevention: true,
                                  postfix: "",
                                  imageUploader: {
                                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                                  allowUrls: true
                                  },
                                  onDemand: true,
                                  discardSelector: ".discard-answer"
                                  ,immediatelyShowMarkdownHelp:true
                                  });


                                  }
                                  });














                                  draft saved

                                  draft discarded


















                                  StackExchange.ready(
                                  function () {
                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4758103%2flast-segment-of-url%23new-answer', 'question_page');
                                  }
                                  );

                                  Post as a guest















                                  Required, but never shown

























                                  22 Answers
                                  22






                                  active

                                  oldest

                                  votes








                                  22 Answers
                                  22






                                  active

                                  oldest

                                  votes









                                  active

                                  oldest

                                  votes






                                  active

                                  oldest

                                  votes









                                  278














                                  You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substr() function to return the substring starting from that location:



                                  window.alert(this.href.substr(this.href.lastIndexOf('/') + 1));


                                  That way, you'll avoid creating an array containing all your URL segments, as split() does.






                                  share|improve this answer





















                                  • 2





                                    @oshirowanen, no, but it will create an array element from each URL segment. Since you're only interested in the last segment, it might be wasteful to allocate many array elements that you'll never use.

                                    – Frédéric Hamidi
                                    Jan 21 '11 at 11:23






                                  • 7





                                    But if the url was become like admin/store/tour/-1/ so it's will be '' string?

                                    – Set Kyar Wa Lar
                                    Aug 20 '14 at 8:39








                                  • 1





                                    @Set, nicer maybe, slower surely.

                                    – Frédéric Hamidi
                                    Aug 20 '14 at 8:58






                                  • 1





                                    For future readers, do not rely on the href attribute, it is unresolved and can contain things like ../ meaning up one directory. Use the native property instead, like this.href.

                                    – Walf
                                    Aug 4 '16 at 0:53








                                  • 3





                                    Attn: @Set Kyar Wa Lar Aug and @Sнаđошƒаӽ Solution for url that contains a / at the end: var url = window.location.href.replace(//$/, ''); /* remove optional end / */ var lastSeg = url.substr(url.lastIndexOf('/') + 1);

                                    – Ross
                                    Nov 2 '16 at 3:18


















                                  278














                                  You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substr() function to return the substring starting from that location:



                                  window.alert(this.href.substr(this.href.lastIndexOf('/') + 1));


                                  That way, you'll avoid creating an array containing all your URL segments, as split() does.






                                  share|improve this answer





















                                  • 2





                                    @oshirowanen, no, but it will create an array element from each URL segment. Since you're only interested in the last segment, it might be wasteful to allocate many array elements that you'll never use.

                                    – Frédéric Hamidi
                                    Jan 21 '11 at 11:23






                                  • 7





                                    But if the url was become like admin/store/tour/-1/ so it's will be '' string?

                                    – Set Kyar Wa Lar
                                    Aug 20 '14 at 8:39








                                  • 1





                                    @Set, nicer maybe, slower surely.

                                    – Frédéric Hamidi
                                    Aug 20 '14 at 8:58






                                  • 1





                                    For future readers, do not rely on the href attribute, it is unresolved and can contain things like ../ meaning up one directory. Use the native property instead, like this.href.

                                    – Walf
                                    Aug 4 '16 at 0:53








                                  • 3





                                    Attn: @Set Kyar Wa Lar Aug and @Sнаđошƒаӽ Solution for url that contains a / at the end: var url = window.location.href.replace(//$/, ''); /* remove optional end / */ var lastSeg = url.substr(url.lastIndexOf('/') + 1);

                                    – Ross
                                    Nov 2 '16 at 3:18
















                                  278












                                  278








                                  278







                                  You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substr() function to return the substring starting from that location:



                                  window.alert(this.href.substr(this.href.lastIndexOf('/') + 1));


                                  That way, you'll avoid creating an array containing all your URL segments, as split() does.






                                  share|improve this answer















                                  You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substr() function to return the substring starting from that location:



                                  window.alert(this.href.substr(this.href.lastIndexOf('/') + 1));


                                  That way, you'll avoid creating an array containing all your URL segments, as split() does.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Sep 27 '16 at 8:01

























                                  answered Jan 21 '11 at 11:18









                                  Frédéric HamidiFrédéric Hamidi

                                  207k31394419




                                  207k31394419








                                  • 2





                                    @oshirowanen, no, but it will create an array element from each URL segment. Since you're only interested in the last segment, it might be wasteful to allocate many array elements that you'll never use.

                                    – Frédéric Hamidi
                                    Jan 21 '11 at 11:23






                                  • 7





                                    But if the url was become like admin/store/tour/-1/ so it's will be '' string?

                                    – Set Kyar Wa Lar
                                    Aug 20 '14 at 8:39








                                  • 1





                                    @Set, nicer maybe, slower surely.

                                    – Frédéric Hamidi
                                    Aug 20 '14 at 8:58






                                  • 1





                                    For future readers, do not rely on the href attribute, it is unresolved and can contain things like ../ meaning up one directory. Use the native property instead, like this.href.

                                    – Walf
                                    Aug 4 '16 at 0:53








                                  • 3





                                    Attn: @Set Kyar Wa Lar Aug and @Sнаđошƒаӽ Solution for url that contains a / at the end: var url = window.location.href.replace(//$/, ''); /* remove optional end / */ var lastSeg = url.substr(url.lastIndexOf('/') + 1);

                                    – Ross
                                    Nov 2 '16 at 3:18
















                                  • 2





                                    @oshirowanen, no, but it will create an array element from each URL segment. Since you're only interested in the last segment, it might be wasteful to allocate many array elements that you'll never use.

                                    – Frédéric Hamidi
                                    Jan 21 '11 at 11:23






                                  • 7





                                    But if the url was become like admin/store/tour/-1/ so it's will be '' string?

                                    – Set Kyar Wa Lar
                                    Aug 20 '14 at 8:39








                                  • 1





                                    @Set, nicer maybe, slower surely.

                                    – Frédéric Hamidi
                                    Aug 20 '14 at 8:58






                                  • 1





                                    For future readers, do not rely on the href attribute, it is unresolved and can contain things like ../ meaning up one directory. Use the native property instead, like this.href.

                                    – Walf
                                    Aug 4 '16 at 0:53








                                  • 3





                                    Attn: @Set Kyar Wa Lar Aug and @Sнаđошƒаӽ Solution for url that contains a / at the end: var url = window.location.href.replace(//$/, ''); /* remove optional end / */ var lastSeg = url.substr(url.lastIndexOf('/') + 1);

                                    – Ross
                                    Nov 2 '16 at 3:18










                                  2




                                  2





                                  @oshirowanen, no, but it will create an array element from each URL segment. Since you're only interested in the last segment, it might be wasteful to allocate many array elements that you'll never use.

                                  – Frédéric Hamidi
                                  Jan 21 '11 at 11:23





                                  @oshirowanen, no, but it will create an array element from each URL segment. Since you're only interested in the last segment, it might be wasteful to allocate many array elements that you'll never use.

                                  – Frédéric Hamidi
                                  Jan 21 '11 at 11:23




                                  7




                                  7





                                  But if the url was become like admin/store/tour/-1/ so it's will be '' string?

                                  – Set Kyar Wa Lar
                                  Aug 20 '14 at 8:39







                                  But if the url was become like admin/store/tour/-1/ so it's will be '' string?

                                  – Set Kyar Wa Lar
                                  Aug 20 '14 at 8:39






                                  1




                                  1





                                  @Set, nicer maybe, slower surely.

                                  – Frédéric Hamidi
                                  Aug 20 '14 at 8:58





                                  @Set, nicer maybe, slower surely.

                                  – Frédéric Hamidi
                                  Aug 20 '14 at 8:58




                                  1




                                  1





                                  For future readers, do not rely on the href attribute, it is unresolved and can contain things like ../ meaning up one directory. Use the native property instead, like this.href.

                                  – Walf
                                  Aug 4 '16 at 0:53







                                  For future readers, do not rely on the href attribute, it is unresolved and can contain things like ../ meaning up one directory. Use the native property instead, like this.href.

                                  – Walf
                                  Aug 4 '16 at 0:53






                                  3




                                  3





                                  Attn: @Set Kyar Wa Lar Aug and @Sнаđошƒаӽ Solution for url that contains a / at the end: var url = window.location.href.replace(//$/, ''); /* remove optional end / */ var lastSeg = url.substr(url.lastIndexOf('/') + 1);

                                  – Ross
                                  Nov 2 '16 at 3:18







                                  Attn: @Set Kyar Wa Lar Aug and @Sнаđошƒаӽ Solution for url that contains a / at the end: var url = window.location.href.replace(//$/, ''); /* remove optional end / */ var lastSeg = url.substr(url.lastIndexOf('/') + 1);

                                  – Ross
                                  Nov 2 '16 at 3:18















                                  115

















                                  var parts = 'http://mywebsite/folder/file'.split('/');
                                  var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash

                                  console.log(lastSegment);








                                  share|improve this answer


























                                  • Can you explain me how it work's? as per my knowledge .pop() used for remove last element of a array. but is here it showed last element of my url!!

                                    – Inspire Shahin
                                    Dec 15 '15 at 7:33






                                  • 1





                                    Split will convert your url into an array taking each section of the url delimited by '/'. Hence the last segment is the last element of both the url and the subsequently created array.

                                    – stephen
                                    Feb 22 '16 at 23:46






                                  • 9





                                    This won't work if the url ends with a "/" i.e. http://mywebsite/folder/file/

                                    – Peter Ludlow
                                    Feb 25 '16 at 4:40


















                                  115

















                                  var parts = 'http://mywebsite/folder/file'.split('/');
                                  var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash

                                  console.log(lastSegment);








                                  share|improve this answer


























                                  • Can you explain me how it work's? as per my knowledge .pop() used for remove last element of a array. but is here it showed last element of my url!!

                                    – Inspire Shahin
                                    Dec 15 '15 at 7:33






                                  • 1





                                    Split will convert your url into an array taking each section of the url delimited by '/'. Hence the last segment is the last element of both the url and the subsequently created array.

                                    – stephen
                                    Feb 22 '16 at 23:46






                                  • 9





                                    This won't work if the url ends with a "/" i.e. http://mywebsite/folder/file/

                                    – Peter Ludlow
                                    Feb 25 '16 at 4:40
















                                  115












                                  115








                                  115










                                  var parts = 'http://mywebsite/folder/file'.split('/');
                                  var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash

                                  console.log(lastSegment);








                                  share|improve this answer


















                                  var parts = 'http://mywebsite/folder/file'.split('/');
                                  var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash

                                  console.log(lastSegment);








                                  var parts = 'http://mywebsite/folder/file'.split('/');
                                  var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash

                                  console.log(lastSegment);





                                  var parts = 'http://mywebsite/folder/file'.split('/');
                                  var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash

                                  console.log(lastSegment);






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jun 24 '17 at 17:12









                                  Chris Happy

                                  4,5631933




                                  4,5631933










                                  answered Oct 28 '12 at 11:35









                                  Tim van OostromTim van Oostrom

                                  1,347195




                                  1,347195













                                  • Can you explain me how it work's? as per my knowledge .pop() used for remove last element of a array. but is here it showed last element of my url!!

                                    – Inspire Shahin
                                    Dec 15 '15 at 7:33






                                  • 1





                                    Split will convert your url into an array taking each section of the url delimited by '/'. Hence the last segment is the last element of both the url and the subsequently created array.

                                    – stephen
                                    Feb 22 '16 at 23:46






                                  • 9





                                    This won't work if the url ends with a "/" i.e. http://mywebsite/folder/file/

                                    – Peter Ludlow
                                    Feb 25 '16 at 4:40





















                                  • Can you explain me how it work's? as per my knowledge .pop() used for remove last element of a array. but is here it showed last element of my url!!

                                    – Inspire Shahin
                                    Dec 15 '15 at 7:33






                                  • 1





                                    Split will convert your url into an array taking each section of the url delimited by '/'. Hence the last segment is the last element of both the url and the subsequently created array.

                                    – stephen
                                    Feb 22 '16 at 23:46






                                  • 9





                                    This won't work if the url ends with a "/" i.e. http://mywebsite/folder/file/

                                    – Peter Ludlow
                                    Feb 25 '16 at 4:40



















                                  Can you explain me how it work's? as per my knowledge .pop() used for remove last element of a array. but is here it showed last element of my url!!

                                  – Inspire Shahin
                                  Dec 15 '15 at 7:33





                                  Can you explain me how it work's? as per my knowledge .pop() used for remove last element of a array. but is here it showed last element of my url!!

                                  – Inspire Shahin
                                  Dec 15 '15 at 7:33




                                  1




                                  1





                                  Split will convert your url into an array taking each section of the url delimited by '/'. Hence the last segment is the last element of both the url and the subsequently created array.

                                  – stephen
                                  Feb 22 '16 at 23:46





                                  Split will convert your url into an array taking each section of the url delimited by '/'. Hence the last segment is the last element of both the url and the subsequently created array.

                                  – stephen
                                  Feb 22 '16 at 23:46




                                  9




                                  9





                                  This won't work if the url ends with a "/" i.e. http://mywebsite/folder/file/

                                  – Peter Ludlow
                                  Feb 25 '16 at 4:40







                                  This won't work if the url ends with a "/" i.e. http://mywebsite/folder/file/

                                  – Peter Ludlow
                                  Feb 25 '16 at 4:40













                                  36














                                  window.location.pathname.split("/").pop()





                                  share|improve this answer
























                                  • simple and easy. Thanks.

                                    – krezaeim
                                    Sep 24 '18 at 18:01











                                  • Perfect and tidy, great

                                    – Babak Habibi
                                    Oct 11 '18 at 12:29
















                                  36














                                  window.location.pathname.split("/").pop()





                                  share|improve this answer
























                                  • simple and easy. Thanks.

                                    – krezaeim
                                    Sep 24 '18 at 18:01











                                  • Perfect and tidy, great

                                    – Babak Habibi
                                    Oct 11 '18 at 12:29














                                  36












                                  36








                                  36







                                  window.location.pathname.split("/").pop()





                                  share|improve this answer













                                  window.location.pathname.split("/").pop()






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Nov 21 '16 at 16:56









                                  Dblock247Dblock247

                                  1,44032340




                                  1,44032340













                                  • simple and easy. Thanks.

                                    – krezaeim
                                    Sep 24 '18 at 18:01











                                  • Perfect and tidy, great

                                    – Babak Habibi
                                    Oct 11 '18 at 12:29



















                                  • simple and easy. Thanks.

                                    – krezaeim
                                    Sep 24 '18 at 18:01











                                  • Perfect and tidy, great

                                    – Babak Habibi
                                    Oct 11 '18 at 12:29

















                                  simple and easy. Thanks.

                                  – krezaeim
                                  Sep 24 '18 at 18:01





                                  simple and easy. Thanks.

                                  – krezaeim
                                  Sep 24 '18 at 18:01













                                  Perfect and tidy, great

                                  – Babak Habibi
                                  Oct 11 '18 at 12:29





                                  Perfect and tidy, great

                                  – Babak Habibi
                                  Oct 11 '18 at 12:29











                                  23














                                  Just another solution with regex.



                                  var href = location.href;
                                  console.log(href.match(/([^/]*)/*$/)[1]);





                                  share|improve this answer



















                                  • 2





                                    this works great if URL ends with /

                                    – Shoaib Iqbal
                                    Nov 14 '16 at 6:00
















                                  23














                                  Just another solution with regex.



                                  var href = location.href;
                                  console.log(href.match(/([^/]*)/*$/)[1]);





                                  share|improve this answer



















                                  • 2





                                    this works great if URL ends with /

                                    – Shoaib Iqbal
                                    Nov 14 '16 at 6:00














                                  23












                                  23








                                  23







                                  Just another solution with regex.



                                  var href = location.href;
                                  console.log(href.match(/([^/]*)/*$/)[1]);





                                  share|improve this answer













                                  Just another solution with regex.



                                  var href = location.href;
                                  console.log(href.match(/([^/]*)/*$/)[1]);






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Apr 20 '16 at 10:56









                                  AvirtumAvirtum

                                  253313




                                  253313








                                  • 2





                                    this works great if URL ends with /

                                    – Shoaib Iqbal
                                    Nov 14 '16 at 6:00














                                  • 2





                                    this works great if URL ends with /

                                    – Shoaib Iqbal
                                    Nov 14 '16 at 6:00








                                  2




                                  2





                                  this works great if URL ends with /

                                  – Shoaib Iqbal
                                  Nov 14 '16 at 6:00





                                  this works great if URL ends with /

                                  – Shoaib Iqbal
                                  Nov 14 '16 at 6:00











                                  16














                                  Javascript has the function split associated to string object that can help you:



                                  var url = "http://mywebsite/folder/file";
                                  var array = url.split('/');

                                  var lastsegment = array[array.length-1];





                                  share|improve this answer




























                                    16














                                    Javascript has the function split associated to string object that can help you:



                                    var url = "http://mywebsite/folder/file";
                                    var array = url.split('/');

                                    var lastsegment = array[array.length-1];





                                    share|improve this answer


























                                      16












                                      16








                                      16







                                      Javascript has the function split associated to string object that can help you:



                                      var url = "http://mywebsite/folder/file";
                                      var array = url.split('/');

                                      var lastsegment = array[array.length-1];





                                      share|improve this answer













                                      Javascript has the function split associated to string object that can help you:



                                      var url = "http://mywebsite/folder/file";
                                      var array = url.split('/');

                                      var lastsegment = array[array.length-1];






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jan 21 '11 at 11:14









                                      Fran VeronaFran Verona

                                      4,12833981




                                      4,12833981























                                          9














                                          Or you could use a regular expression:



                                          alert(href.replace(/.*//, ''));





                                          share|improve this answer




























                                            9














                                            Or you could use a regular expression:



                                            alert(href.replace(/.*//, ''));





                                            share|improve this answer


























                                              9












                                              9








                                              9







                                              Or you could use a regular expression:



                                              alert(href.replace(/.*//, ''));





                                              share|improve this answer













                                              Or you could use a regular expression:



                                              alert(href.replace(/.*//, ''));






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Jan 21 '11 at 11:21









                                              jasssonpetjasssonpet

                                              1,8391215




                                              1,8391215























                                                  8














                                                  var urlChunks = 'mywebsite/folder/file'.split('/');
                                                  alert(urlChunks[urlChunks.length - 1]);





                                                  share|improve this answer




























                                                    8














                                                    var urlChunks = 'mywebsite/folder/file'.split('/');
                                                    alert(urlChunks[urlChunks.length - 1]);





                                                    share|improve this answer


























                                                      8












                                                      8








                                                      8







                                                      var urlChunks = 'mywebsite/folder/file'.split('/');
                                                      alert(urlChunks[urlChunks.length - 1]);





                                                      share|improve this answer













                                                      var urlChunks = 'mywebsite/folder/file'.split('/');
                                                      alert(urlChunks[urlChunks.length - 1]);






                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Jan 21 '11 at 11:14









                                                      acmeacme

                                                      9,96065699




                                                      9,96065699























                                                          5














                                                          I know, it is too late, but for others:
                                                          I highly recommended use PURL jquery plugin. Motivation for PURL is that url can be segmented by '#' too (example: angular.js links), i.e. url could looks like



                                                              http://test.com/#/about/us/


                                                          or



                                                              http://test.com/#sky=blue&grass=green


                                                          And with PURL you can easy decide (segment/fsegment) which segment you want to get.



                                                          For "classic" last segment you could write:



                                                              var url = $.url('http://test.com/dir/index.html?key=value');
                                                          var lastSegment = url.segment().pop(); // index.html





                                                          share|improve this answer




























                                                            5














                                                            I know, it is too late, but for others:
                                                            I highly recommended use PURL jquery plugin. Motivation for PURL is that url can be segmented by '#' too (example: angular.js links), i.e. url could looks like



                                                                http://test.com/#/about/us/


                                                            or



                                                                http://test.com/#sky=blue&grass=green


                                                            And with PURL you can easy decide (segment/fsegment) which segment you want to get.



                                                            For "classic" last segment you could write:



                                                                var url = $.url('http://test.com/dir/index.html?key=value');
                                                            var lastSegment = url.segment().pop(); // index.html





                                                            share|improve this answer


























                                                              5












                                                              5








                                                              5







                                                              I know, it is too late, but for others:
                                                              I highly recommended use PURL jquery plugin. Motivation for PURL is that url can be segmented by '#' too (example: angular.js links), i.e. url could looks like



                                                                  http://test.com/#/about/us/


                                                              or



                                                                  http://test.com/#sky=blue&grass=green


                                                              And with PURL you can easy decide (segment/fsegment) which segment you want to get.



                                                              For "classic" last segment you could write:



                                                                  var url = $.url('http://test.com/dir/index.html?key=value');
                                                              var lastSegment = url.segment().pop(); // index.html





                                                              share|improve this answer













                                                              I know, it is too late, but for others:
                                                              I highly recommended use PURL jquery plugin. Motivation for PURL is that url can be segmented by '#' too (example: angular.js links), i.e. url could looks like



                                                                  http://test.com/#/about/us/


                                                              or



                                                                  http://test.com/#sky=blue&grass=green


                                                              And with PURL you can easy decide (segment/fsegment) which segment you want to get.



                                                              For "classic" last segment you could write:



                                                                  var url = $.url('http://test.com/dir/index.html?key=value');
                                                              var lastSegment = url.segment().pop(); // index.html






                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Jun 20 '13 at 13:10









                                                              IL55IL55

                                                              455613




                                                              455613























                                                                  4














                                                                  Building on Frédéric's answer using only javascript:



                                                                  var url = document.URL

                                                                  window.alert(url.substr(url.lastIndexOf('/') + 1));





                                                                  share|improve this answer




























                                                                    4














                                                                    Building on Frédéric's answer using only javascript:



                                                                    var url = document.URL

                                                                    window.alert(url.substr(url.lastIndexOf('/') + 1));





                                                                    share|improve this answer


























                                                                      4












                                                                      4








                                                                      4







                                                                      Building on Frédéric's answer using only javascript:



                                                                      var url = document.URL

                                                                      window.alert(url.substr(url.lastIndexOf('/') + 1));





                                                                      share|improve this answer













                                                                      Building on Frédéric's answer using only javascript:



                                                                      var url = document.URL

                                                                      window.alert(url.substr(url.lastIndexOf('/') + 1));






                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered Jan 13 '15 at 18:02









                                                                      PinchPinch

                                                                      2,50052652




                                                                      2,50052652























                                                                          3














                                                                          Also,



                                                                          var url = $(this).attr("href");
                                                                          var part = url.substring(url.lastIndexOf('/') + 1);





                                                                          share|improve this answer




























                                                                            3














                                                                            Also,



                                                                            var url = $(this).attr("href");
                                                                            var part = url.substring(url.lastIndexOf('/') + 1);





                                                                            share|improve this answer


























                                                                              3












                                                                              3








                                                                              3







                                                                              Also,



                                                                              var url = $(this).attr("href");
                                                                              var part = url.substring(url.lastIndexOf('/') + 1);





                                                                              share|improve this answer













                                                                              Also,



                                                                              var url = $(this).attr("href");
                                                                              var part = url.substring(url.lastIndexOf('/') + 1);






                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Jan 21 '11 at 11:18









                                                                              naveennaveen

                                                                              37k36138216




                                                                              37k36138216























                                                                                  3














                                                                                  If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).



                                                                                  url.split('/').filter(function (s) { return !!s }).pop()





                                                                                  share|improve this answer




























                                                                                    3














                                                                                    If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).



                                                                                    url.split('/').filter(function (s) { return !!s }).pop()





                                                                                    share|improve this answer


























                                                                                      3












                                                                                      3








                                                                                      3







                                                                                      If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).



                                                                                      url.split('/').filter(function (s) { return !!s }).pop()





                                                                                      share|improve this answer













                                                                                      If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).



                                                                                      url.split('/').filter(function (s) { return !!s }).pop()






                                                                                      share|improve this answer












                                                                                      share|improve this answer



                                                                                      share|improve this answer










                                                                                      answered May 11 '15 at 16:24









                                                                                      Jaboc83Jaboc83

                                                                                      12217




                                                                                      12217























                                                                                          3














                                                                                          // Store original location in loc like: http://test.com/one/ (ending slash)
                                                                                          var loc = location.href;
                                                                                          // If the last char is a slash trim it, otherwise return the original loc
                                                                                          loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
                                                                                          var targetValue = loc.substr(loc.lastIndexOf('/') + 1);


                                                                                          targetValue = one



                                                                                          If your url looks like:




                                                                                          http://test.com/one/




                                                                                          or




                                                                                          http://test.com/one




                                                                                          or




                                                                                          http://test.com/one/index.htm




                                                                                          Then loc ends up looking like:
                                                                                          http://test.com/one



                                                                                          Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.



                                                                                          var targetValue = loc.substr(loc.lastIndexOf('/') + 1);





                                                                                          share|improve this answer


























                                                                                          • I probably miss something, but with "test.com/one" loc ends up looking like : "test.com". I think it should be like : if( loc.lastIndexOf('/') == (loc.length -1) ){ loc = loc.substr(0,loc.length-1) }else{ var isFile = loc.substr(loc.lastIndexOf('/'),loc.length).indexOf('.') != -1; if(isFile) loc = loc.substr(0,loc.lastIndexOf('/')); }

                                                                                            – Allan Raquin
                                                                                            Aug 3 '16 at 13:53











                                                                                          • Fails if slash in search or hash.

                                                                                            – Walf
                                                                                            Aug 4 '16 at 0:42
















                                                                                          3














                                                                                          // Store original location in loc like: http://test.com/one/ (ending slash)
                                                                                          var loc = location.href;
                                                                                          // If the last char is a slash trim it, otherwise return the original loc
                                                                                          loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
                                                                                          var targetValue = loc.substr(loc.lastIndexOf('/') + 1);


                                                                                          targetValue = one



                                                                                          If your url looks like:




                                                                                          http://test.com/one/




                                                                                          or




                                                                                          http://test.com/one




                                                                                          or




                                                                                          http://test.com/one/index.htm




                                                                                          Then loc ends up looking like:
                                                                                          http://test.com/one



                                                                                          Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.



                                                                                          var targetValue = loc.substr(loc.lastIndexOf('/') + 1);





                                                                                          share|improve this answer


























                                                                                          • I probably miss something, but with "test.com/one" loc ends up looking like : "test.com". I think it should be like : if( loc.lastIndexOf('/') == (loc.length -1) ){ loc = loc.substr(0,loc.length-1) }else{ var isFile = loc.substr(loc.lastIndexOf('/'),loc.length).indexOf('.') != -1; if(isFile) loc = loc.substr(0,loc.lastIndexOf('/')); }

                                                                                            – Allan Raquin
                                                                                            Aug 3 '16 at 13:53











                                                                                          • Fails if slash in search or hash.

                                                                                            – Walf
                                                                                            Aug 4 '16 at 0:42














                                                                                          3












                                                                                          3








                                                                                          3







                                                                                          // Store original location in loc like: http://test.com/one/ (ending slash)
                                                                                          var loc = location.href;
                                                                                          // If the last char is a slash trim it, otherwise return the original loc
                                                                                          loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
                                                                                          var targetValue = loc.substr(loc.lastIndexOf('/') + 1);


                                                                                          targetValue = one



                                                                                          If your url looks like:




                                                                                          http://test.com/one/




                                                                                          or




                                                                                          http://test.com/one




                                                                                          or




                                                                                          http://test.com/one/index.htm




                                                                                          Then loc ends up looking like:
                                                                                          http://test.com/one



                                                                                          Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.



                                                                                          var targetValue = loc.substr(loc.lastIndexOf('/') + 1);





                                                                                          share|improve this answer















                                                                                          // Store original location in loc like: http://test.com/one/ (ending slash)
                                                                                          var loc = location.href;
                                                                                          // If the last char is a slash trim it, otherwise return the original loc
                                                                                          loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
                                                                                          var targetValue = loc.substr(loc.lastIndexOf('/') + 1);


                                                                                          targetValue = one



                                                                                          If your url looks like:




                                                                                          http://test.com/one/




                                                                                          or




                                                                                          http://test.com/one




                                                                                          or




                                                                                          http://test.com/one/index.htm




                                                                                          Then loc ends up looking like:
                                                                                          http://test.com/one



                                                                                          Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.



                                                                                          var targetValue = loc.substr(loc.lastIndexOf('/') + 1);






                                                                                          share|improve this answer














                                                                                          share|improve this answer



                                                                                          share|improve this answer








                                                                                          edited Jun 16 '16 at 12:29









                                                                                          bleakgadfly

                                                                                          84321630




                                                                                          84321630










                                                                                          answered Jun 17 '15 at 19:19









                                                                                          raddevusraddevus

                                                                                          2,75433042




                                                                                          2,75433042













                                                                                          • I probably miss something, but with "test.com/one" loc ends up looking like : "test.com". I think it should be like : if( loc.lastIndexOf('/') == (loc.length -1) ){ loc = loc.substr(0,loc.length-1) }else{ var isFile = loc.substr(loc.lastIndexOf('/'),loc.length).indexOf('.') != -1; if(isFile) loc = loc.substr(0,loc.lastIndexOf('/')); }

                                                                                            – Allan Raquin
                                                                                            Aug 3 '16 at 13:53











                                                                                          • Fails if slash in search or hash.

                                                                                            – Walf
                                                                                            Aug 4 '16 at 0:42



















                                                                                          • I probably miss something, but with "test.com/one" loc ends up looking like : "test.com". I think it should be like : if( loc.lastIndexOf('/') == (loc.length -1) ){ loc = loc.substr(0,loc.length-1) }else{ var isFile = loc.substr(loc.lastIndexOf('/'),loc.length).indexOf('.') != -1; if(isFile) loc = loc.substr(0,loc.lastIndexOf('/')); }

                                                                                            – Allan Raquin
                                                                                            Aug 3 '16 at 13:53











                                                                                          • Fails if slash in search or hash.

                                                                                            – Walf
                                                                                            Aug 4 '16 at 0:42

















                                                                                          I probably miss something, but with "test.com/one" loc ends up looking like : "test.com". I think it should be like : if( loc.lastIndexOf('/') == (loc.length -1) ){ loc = loc.substr(0,loc.length-1) }else{ var isFile = loc.substr(loc.lastIndexOf('/'),loc.length).indexOf('.') != -1; if(isFile) loc = loc.substr(0,loc.lastIndexOf('/')); }

                                                                                          – Allan Raquin
                                                                                          Aug 3 '16 at 13:53





                                                                                          I probably miss something, but with "test.com/one" loc ends up looking like : "test.com". I think it should be like : if( loc.lastIndexOf('/') == (loc.length -1) ){ loc = loc.substr(0,loc.length-1) }else{ var isFile = loc.substr(loc.lastIndexOf('/'),loc.length).indexOf('.') != -1; if(isFile) loc = loc.substr(0,loc.lastIndexOf('/')); }

                                                                                          – Allan Raquin
                                                                                          Aug 3 '16 at 13:53













                                                                                          Fails if slash in search or hash.

                                                                                          – Walf
                                                                                          Aug 4 '16 at 0:42





                                                                                          Fails if slash in search or hash.

                                                                                          – Walf
                                                                                          Aug 4 '16 at 0:42











                                                                                          3














                                                                                          window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));


                                                                                          Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.



                                                                                          If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:



                                                                                          window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);





                                                                                          share|improve this answer


























                                                                                          • Also want to add that pathname strips query parameters, but href does not.

                                                                                            – Max Heiber
                                                                                            Aug 3 '16 at 15:33
















                                                                                          3














                                                                                          window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));


                                                                                          Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.



                                                                                          If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:



                                                                                          window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);





                                                                                          share|improve this answer


























                                                                                          • Also want to add that pathname strips query parameters, but href does not.

                                                                                            – Max Heiber
                                                                                            Aug 3 '16 at 15:33














                                                                                          3












                                                                                          3








                                                                                          3







                                                                                          window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));


                                                                                          Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.



                                                                                          If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:



                                                                                          window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);





                                                                                          share|improve this answer















                                                                                          window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));


                                                                                          Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.



                                                                                          If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:



                                                                                          window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);






                                                                                          share|improve this answer














                                                                                          share|improve this answer



                                                                                          share|improve this answer








                                                                                          edited Aug 4 '16 at 0:48

























                                                                                          answered Jan 21 '11 at 11:43









                                                                                          WalfWalf

                                                                                          4,43312242




                                                                                          4,43312242













                                                                                          • Also want to add that pathname strips query parameters, but href does not.

                                                                                            – Max Heiber
                                                                                            Aug 3 '16 at 15:33



















                                                                                          • Also want to add that pathname strips query parameters, but href does not.

                                                                                            – Max Heiber
                                                                                            Aug 3 '16 at 15:33

















                                                                                          Also want to add that pathname strips query parameters, but href does not.

                                                                                          – Max Heiber
                                                                                          Aug 3 '16 at 15:33





                                                                                          Also want to add that pathname strips query parameters, but href does not.

                                                                                          – Max Heiber
                                                                                          Aug 3 '16 at 15:33











                                                                                          3














                                                                                          The other answers may work if the path is simple, consisting only of simple path elements. But when it contains query params as well, they break.



                                                                                          Better use URL object for this instead to get a more robust solution. It is a parsed interpretation of the present URL:



                                                                                          Input: const href = 'https://stackoverflow.com/boo?q=foo&s=bar'



                                                                                          const last = new URL(href).pathname.split('/').pop();
                                                                                          console.log(last);


                                                                                          Output: 'boo'






                                                                                          share|improve this answer






























                                                                                            3














                                                                                            The other answers may work if the path is simple, consisting only of simple path elements. But when it contains query params as well, they break.



                                                                                            Better use URL object for this instead to get a more robust solution. It is a parsed interpretation of the present URL:



                                                                                            Input: const href = 'https://stackoverflow.com/boo?q=foo&s=bar'



                                                                                            const last = new URL(href).pathname.split('/').pop();
                                                                                            console.log(last);


                                                                                            Output: 'boo'






                                                                                            share|improve this answer




























                                                                                              3












                                                                                              3








                                                                                              3







                                                                                              The other answers may work if the path is simple, consisting only of simple path elements. But when it contains query params as well, they break.



                                                                                              Better use URL object for this instead to get a more robust solution. It is a parsed interpretation of the present URL:



                                                                                              Input: const href = 'https://stackoverflow.com/boo?q=foo&s=bar'



                                                                                              const last = new URL(href).pathname.split('/').pop();
                                                                                              console.log(last);


                                                                                              Output: 'boo'






                                                                                              share|improve this answer















                                                                                              The other answers may work if the path is simple, consisting only of simple path elements. But when it contains query params as well, they break.



                                                                                              Better use URL object for this instead to get a more robust solution. It is a parsed interpretation of the present URL:



                                                                                              Input: const href = 'https://stackoverflow.com/boo?q=foo&s=bar'



                                                                                              const last = new URL(href).pathname.split('/').pop();
                                                                                              console.log(last);


                                                                                              Output: 'boo'







                                                                                              share|improve this answer














                                                                                              share|improve this answer



                                                                                              share|improve this answer








                                                                                              edited Nov 19 '18 at 21:10

























                                                                                              answered Aug 10 '18 at 23:27









                                                                                              Sebastian BarthSebastian Barth

                                                                                              1,60632537




                                                                                              1,60632537























                                                                                                  2














                                                                                                  var pathname = window.location.pathname; // Returns path only
                                                                                                  var url = window.location.href; // Returns full URL


                                                                                                  Copied from this answer






                                                                                                  share|improve this answer






























                                                                                                    2














                                                                                                    var pathname = window.location.pathname; // Returns path only
                                                                                                    var url = window.location.href; // Returns full URL


                                                                                                    Copied from this answer






                                                                                                    share|improve this answer




























                                                                                                      2












                                                                                                      2








                                                                                                      2







                                                                                                      var pathname = window.location.pathname; // Returns path only
                                                                                                      var url = window.location.href; // Returns full URL


                                                                                                      Copied from this answer






                                                                                                      share|improve this answer















                                                                                                      var pathname = window.location.pathname; // Returns path only
                                                                                                      var url = window.location.href; // Returns full URL


                                                                                                      Copied from this answer







                                                                                                      share|improve this answer














                                                                                                      share|improve this answer



                                                                                                      share|improve this answer








                                                                                                      edited May 23 '17 at 12:02









                                                                                                      Community

                                                                                                      11




                                                                                                      11










                                                                                                      answered Jan 14 '16 at 16:02









                                                                                                      Roberto AlonsoRoberto Alonso

                                                                                                      53445




                                                                                                      53445























                                                                                                          2














                                                                                                          To get the last segment of your current window:



                                                                                                          window.location.href.substr(window.location.href.lastIndexOf('/') +1)






                                                                                                          share|improve this answer




























                                                                                                            2














                                                                                                            To get the last segment of your current window:



                                                                                                            window.location.href.substr(window.location.href.lastIndexOf('/') +1)






                                                                                                            share|improve this answer


























                                                                                                              2












                                                                                                              2








                                                                                                              2







                                                                                                              To get the last segment of your current window:



                                                                                                              window.location.href.substr(window.location.href.lastIndexOf('/') +1)






                                                                                                              share|improve this answer













                                                                                                              To get the last segment of your current window:



                                                                                                              window.location.href.substr(window.location.href.lastIndexOf('/') +1)







                                                                                                              share|improve this answer












                                                                                                              share|improve this answer



                                                                                                              share|improve this answer










                                                                                                              answered May 23 '17 at 10:31









                                                                                                              developerdeveloper

                                                                                                              1,125625




                                                                                                              1,125625























                                                                                                                  1














                                                                                                                  Updated raddevus answer :



                                                                                                                  var loc = window.location.href;
                                                                                                                  loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
                                                                                                                  var targetValue = loc.substr(loc.lastIndexOf('/') + 1);


                                                                                                                  Prints last path of url as string :



                                                                                                                  test.com/path-name = path-name

                                                                                                                  test.com/path-name/ = path-name





                                                                                                                  share|improve this answer






























                                                                                                                    1














                                                                                                                    Updated raddevus answer :



                                                                                                                    var loc = window.location.href;
                                                                                                                    loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
                                                                                                                    var targetValue = loc.substr(loc.lastIndexOf('/') + 1);


                                                                                                                    Prints last path of url as string :



                                                                                                                    test.com/path-name = path-name

                                                                                                                    test.com/path-name/ = path-name





                                                                                                                    share|improve this answer




























                                                                                                                      1












                                                                                                                      1








                                                                                                                      1







                                                                                                                      Updated raddevus answer :



                                                                                                                      var loc = window.location.href;
                                                                                                                      loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
                                                                                                                      var targetValue = loc.substr(loc.lastIndexOf('/') + 1);


                                                                                                                      Prints last path of url as string :



                                                                                                                      test.com/path-name = path-name

                                                                                                                      test.com/path-name/ = path-name





                                                                                                                      share|improve this answer















                                                                                                                      Updated raddevus answer :



                                                                                                                      var loc = window.location.href;
                                                                                                                      loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
                                                                                                                      var targetValue = loc.substr(loc.lastIndexOf('/') + 1);


                                                                                                                      Prints last path of url as string :



                                                                                                                      test.com/path-name = path-name

                                                                                                                      test.com/path-name/ = path-name






                                                                                                                      share|improve this answer














                                                                                                                      share|improve this answer



                                                                                                                      share|improve this answer








                                                                                                                      edited Feb 21 '18 at 13:35









                                                                                                                      F0XS

                                                                                                                      1,25631119




                                                                                                                      1,25631119










                                                                                                                      answered Feb 21 '18 at 13:01









                                                                                                                      Nemanja SmiljanicNemanja Smiljanic

                                                                                                                      112




                                                                                                                      112























                                                                                                                          1














                                                                                                                          Returns the last segment, regardless of trailing slashes:






                                                                                                                          var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();

                                                                                                                          console.log(val);








                                                                                                                          share|improve this answer






























                                                                                                                            1














                                                                                                                            Returns the last segment, regardless of trailing slashes:






                                                                                                                            var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();

                                                                                                                            console.log(val);








                                                                                                                            share|improve this answer




























                                                                                                                              1












                                                                                                                              1








                                                                                                                              1







                                                                                                                              Returns the last segment, regardless of trailing slashes:






                                                                                                                              var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();

                                                                                                                              console.log(val);








                                                                                                                              share|improve this answer















                                                                                                                              Returns the last segment, regardless of trailing slashes:






                                                                                                                              var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();

                                                                                                                              console.log(val);








                                                                                                                              var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();

                                                                                                                              console.log(val);





                                                                                                                              var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();

                                                                                                                              console.log(val);






                                                                                                                              share|improve this answer














                                                                                                                              share|improve this answer



                                                                                                                              share|improve this answer








                                                                                                                              edited Oct 6 '18 at 16:47

























                                                                                                                              answered Aug 21 '18 at 12:46









                                                                                                                              John DohertyJohn Doherty

                                                                                                                              1,141916




                                                                                                                              1,141916























                                                                                                                                  0














                                                                                                                                  I believe it's safer to remove the tail slash('/') before doing substring. Because I got an empty string in my scenario.



                                                                                                                                  window.alert((window.location.pathname).replace(//$/, "").substr((window.location.pathname.replace(//$/, "")).lastIndexOf('/') + 1));





                                                                                                                                  share|improve this answer




























                                                                                                                                    0














                                                                                                                                    I believe it's safer to remove the tail slash('/') before doing substring. Because I got an empty string in my scenario.



                                                                                                                                    window.alert((window.location.pathname).replace(//$/, "").substr((window.location.pathname.replace(//$/, "")).lastIndexOf('/') + 1));





                                                                                                                                    share|improve this answer


























                                                                                                                                      0












                                                                                                                                      0








                                                                                                                                      0







                                                                                                                                      I believe it's safer to remove the tail slash('/') before doing substring. Because I got an empty string in my scenario.



                                                                                                                                      window.alert((window.location.pathname).replace(//$/, "").substr((window.location.pathname.replace(//$/, "")).lastIndexOf('/') + 1));





                                                                                                                                      share|improve this answer













                                                                                                                                      I believe it's safer to remove the tail slash('/') before doing substring. Because I got an empty string in my scenario.



                                                                                                                                      window.alert((window.location.pathname).replace(//$/, "").substr((window.location.pathname.replace(//$/, "")).lastIndexOf('/') + 1));






                                                                                                                                      share|improve this answer












                                                                                                                                      share|improve this answer



                                                                                                                                      share|improve this answer










                                                                                                                                      answered May 22 '18 at 12:34









                                                                                                                                      JaisonJaison

                                                                                                                                      1,89011825




                                                                                                                                      1,89011825























                                                                                                                                          0














                                                                                                                                          I am using regex and split:



                                                                                                                                          var last_path = location.href.match(/./(.[w])/)[1].split("#")[0].split("?")[0]



                                                                                                                                          In the end it will ignore # ? & / ending urls, which happens a lot. Example:



                                                                                                                                          https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm



                                                                                                                                          https://cardsrealm.com/profile/cardsRealm#hello -> Returns cardsRealm



                                                                                                                                          https://cardsrealm.com/profile/cardsRealm?hello -> Returns cardsRealm



                                                                                                                                          https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm






                                                                                                                                          share|improve this answer






























                                                                                                                                            0














                                                                                                                                            I am using regex and split:



                                                                                                                                            var last_path = location.href.match(/./(.[w])/)[1].split("#")[0].split("?")[0]



                                                                                                                                            In the end it will ignore # ? & / ending urls, which happens a lot. Example:



                                                                                                                                            https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm



                                                                                                                                            https://cardsrealm.com/profile/cardsRealm#hello -> Returns cardsRealm



                                                                                                                                            https://cardsrealm.com/profile/cardsRealm?hello -> Returns cardsRealm



                                                                                                                                            https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm






                                                                                                                                            share|improve this answer




























                                                                                                                                              0












                                                                                                                                              0








                                                                                                                                              0







                                                                                                                                              I am using regex and split:



                                                                                                                                              var last_path = location.href.match(/./(.[w])/)[1].split("#")[0].split("?")[0]



                                                                                                                                              In the end it will ignore # ? & / ending urls, which happens a lot. Example:



                                                                                                                                              https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm



                                                                                                                                              https://cardsrealm.com/profile/cardsRealm#hello -> Returns cardsRealm



                                                                                                                                              https://cardsrealm.com/profile/cardsRealm?hello -> Returns cardsRealm



                                                                                                                                              https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm






                                                                                                                                              share|improve this answer















                                                                                                                                              I am using regex and split:



                                                                                                                                              var last_path = location.href.match(/./(.[w])/)[1].split("#")[0].split("?")[0]



                                                                                                                                              In the end it will ignore # ? & / ending urls, which happens a lot. Example:



                                                                                                                                              https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm



                                                                                                                                              https://cardsrealm.com/profile/cardsRealm#hello -> Returns cardsRealm



                                                                                                                                              https://cardsrealm.com/profile/cardsRealm?hello -> Returns cardsRealm



                                                                                                                                              https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm







                                                                                                                                              share|improve this answer














                                                                                                                                              share|improve this answer



                                                                                                                                              share|improve this answer








                                                                                                                                              edited Jul 24 '18 at 4:07

























                                                                                                                                              answered Jul 24 '18 at 3:45









                                                                                                                                              DinidinizDinidiniz

                                                                                                                                              17819




                                                                                                                                              17819























                                                                                                                                                  0














                                                                                                                                                  you can first remove if there is / at the end and then get last part of url



                                                                                                                                                  let locationLastPart = window.location.pathname
                                                                                                                                                  if (locationLastPart.substring(locationLastPart.length-1) == "/") {
                                                                                                                                                  locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
                                                                                                                                                  }
                                                                                                                                                  locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);





                                                                                                                                                  share|improve this answer




























                                                                                                                                                    0














                                                                                                                                                    you can first remove if there is / at the end and then get last part of url



                                                                                                                                                    let locationLastPart = window.location.pathname
                                                                                                                                                    if (locationLastPart.substring(locationLastPart.length-1) == "/") {
                                                                                                                                                    locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
                                                                                                                                                    }
                                                                                                                                                    locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);





                                                                                                                                                    share|improve this answer


























                                                                                                                                                      0












                                                                                                                                                      0








                                                                                                                                                      0







                                                                                                                                                      you can first remove if there is / at the end and then get last part of url



                                                                                                                                                      let locationLastPart = window.location.pathname
                                                                                                                                                      if (locationLastPart.substring(locationLastPart.length-1) == "/") {
                                                                                                                                                      locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
                                                                                                                                                      }
                                                                                                                                                      locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);





                                                                                                                                                      share|improve this answer













                                                                                                                                                      you can first remove if there is / at the end and then get last part of url



                                                                                                                                                      let locationLastPart = window.location.pathname
                                                                                                                                                      if (locationLastPart.substring(locationLastPart.length-1) == "/") {
                                                                                                                                                      locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
                                                                                                                                                      }
                                                                                                                                                      locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);






                                                                                                                                                      share|improve this answer












                                                                                                                                                      share|improve this answer



                                                                                                                                                      share|improve this answer










                                                                                                                                                      answered Aug 1 '18 at 14:49









                                                                                                                                                      Veysi YILDIZVeysi YILDIZ

                                                                                                                                                      212




                                                                                                                                                      212























                                                                                                                                                          0














                                                                                                                                                          I don't really know if regex is the right way to solve this issue as it can really affect efficiency of your code, but the below regex will help you fetch the last segment and it will still give you the last segment even if the URL is followed by an empty /. The regex that I came up with is:



                                                                                                                                                          [^/]+[/]?$





                                                                                                                                                          share|improve this answer




























                                                                                                                                                            0














                                                                                                                                                            I don't really know if regex is the right way to solve this issue as it can really affect efficiency of your code, but the below regex will help you fetch the last segment and it will still give you the last segment even if the URL is followed by an empty /. The regex that I came up with is:



                                                                                                                                                            [^/]+[/]?$





                                                                                                                                                            share|improve this answer


























                                                                                                                                                              0












                                                                                                                                                              0








                                                                                                                                                              0







                                                                                                                                                              I don't really know if regex is the right way to solve this issue as it can really affect efficiency of your code, but the below regex will help you fetch the last segment and it will still give you the last segment even if the URL is followed by an empty /. The regex that I came up with is:



                                                                                                                                                              [^/]+[/]?$





                                                                                                                                                              share|improve this answer













                                                                                                                                                              I don't really know if regex is the right way to solve this issue as it can really affect efficiency of your code, but the below regex will help you fetch the last segment and it will still give you the last segment even if the URL is followed by an empty /. The regex that I came up with is:



                                                                                                                                                              [^/]+[/]?$






                                                                                                                                                              share|improve this answer












                                                                                                                                                              share|improve this answer



                                                                                                                                                              share|improve this answer










                                                                                                                                                              answered Aug 27 '18 at 12:40







                                                                                                                                                              user9628338





































                                                                                                                                                                  draft saved

                                                                                                                                                                  draft discarded




















































                                                                                                                                                                  Thanks for contributing an answer to Stack Overflow!


                                                                                                                                                                  • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                                                  But avoid



                                                                                                                                                                  • Asking for help, clarification, or responding to other answers.

                                                                                                                                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                                                  To learn more, see our tips on writing great answers.




                                                                                                                                                                  draft saved


                                                                                                                                                                  draft discarded














                                                                                                                                                                  StackExchange.ready(
                                                                                                                                                                  function () {
                                                                                                                                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4758103%2flast-segment-of-url%23new-answer', 'question_page');
                                                                                                                                                                  }
                                                                                                                                                                  );

                                                                                                                                                                  Post as a guest















                                                                                                                                                                  Required, but never shown





















































                                                                                                                                                                  Required, but never shown














                                                                                                                                                                  Required, but never shown












                                                                                                                                                                  Required, but never shown







                                                                                                                                                                  Required, but never shown

































                                                                                                                                                                  Required, but never shown














                                                                                                                                                                  Required, but never shown












                                                                                                                                                                  Required, but never shown







                                                                                                                                                                  Required, but never shown







                                                                                                                                                                  Popular posts from this blog

                                                                                                                                                                  MongoDB - Not Authorized To Execute Command

                                                                                                                                                                  Npm cannot find a required file even through it is in the searched directory

                                                                                                                                                                  in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith