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.

1
  • Does this answer your question? Last segment of URL Commented Jul 2, 2020 at 21:46

7 Answers 7

16

you can try this:

s="http://localhost:8888/#!/path/somevalue/needthis"
var final = s.substr(s.lastIndexOf('/') + 1);
alert(final)
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

Since you are using angularjs, you can use:

$location.path().split('/').pop();

Comments

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

Comments

0

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.