5

Given an href like:

http://localhost:8888/#!/path/somevalue/needthis

How can I get the last value in the path string (aka: "needthis")?

I tried using window.location.pathname, which gives "/".

I also tried using Angular's $location, which doesn't provide the last value.

user3871
  • 12,432
  • 33
  • 128
  • 268
  • Does this answer your question? [Last segment of URL](https://stackoverflow.com/questions/4758103/last-segment-of-url) – Ivar Jul 02 '20 at 21:46

7 Answers7

16

you can try this:

s="http://localhost:8888/#!/path/somevalue/needthis"
var final = s.substr(s.lastIndexOf('/') + 1);
alert(final)
David Untama
  • 488
  • 3
  • 18
3

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

Himanshu Tanwar
  • 906
  • 6
  • 18
1

what I would do is make a function that takes an index of what part you want.. that way you can get any part anytime

getPathPart = function(index){
    if (index === undefined)
        index = 0;

    var path = window.location.pathname,
        parts = path.split('/');

    if (parts && parts.length > 1)
        parts = (parts || []).splice(1);

    return parts.length > index ? parts[index] : null;
}

with this you can of course make changes like a getLastIndex flag that when true you can return that..

getPathPart = function(index, getLastIndex){
    if (index === undefined)
        index = 0;

    var path = window.location.pathname,
        parts = path.split('/');

    if (parts && parts.length > 1)
        parts = (parts || []).splice(1);

    if(getLastIndex){
        return parts[parts.length - 1]
    }  

    return parts.length > index ? parts[index] : null;
}
John Ruddell
  • 25,283
  • 6
  • 57
  • 86
1

Since you are using angularjs, you can use:

$location.path().split('/').pop();
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

Reverse the string, then do a substring from the beginning of the reversed string to the first occurrence of "/" .

Sam
  • 110
  • 1
  • 9
0

Something like this:

var string = "http://localhost:8888/#!/path/somevalue/needthis";
var segments = string.split("/");
var last = segments[segments.length-1];
console.log(last);
Alex
  • 8,353
  • 9
  • 45
  • 56
0

You could also use a regular expression for this:

var fullPath = 'http://localhost:8888/#!/path/somevalue/needthis',
    result = fullPath.match(/(\w*)$/gi),
    path = (result)? result[0] : '';

this way path would have the last chunk of text from the URL

Matias
  • 641
  • 5
  • 17