IAmYourFaja
IAmYourFaja

Reputation: 56944

How to extract end of URL in Javascript?

I have URLs in the form:

serverName/app/image/thumbnail/2012/4/23/1335228884300/bb65efd50ade4b3591dcf7f4c693042b

Where serverName is the domain name of the server.

I would like to write a JS function that accepts one of these URLs and returns the very last (right-most) forward-slash-delimited string. So if the URL above was passed into the function, it would return "bb65efd50ade4b3591dcf7f4c693042b";.

function getImageDirectoryByFullURL(url) {
    // ... Not sure how to define regexp to delimit on forward slashes,
    // or how to start searching from end of string.
}

Upvotes: 9

Views: 10307

Answers (5)

RobG
RobG

Reputation: 147513

Since there are no sensible regular expression versions, consider:

return url.replace(/^.*\//,'');

Upvotes: 1

Joseph
Joseph

Reputation: 119877

split by slashes /, pop off the last and return it

function getImageDirectoryByFullURL(url){
    return url.split('/').pop()
}

//a step by step breakdown
function getImageDirectoryByFullURL(url){
    url = url.split('/'); //url = ["serverName","app",...,"bb65efd50ade4b3591dcf7f4c693042b"]
    url = url.pop();      //url = "bb65efd50ade4b3591dcf7f4c693042b"
    return url;           //return "bb65efd50ade4b3591dcf7f4c693042b"
}

what this does is split the url per / and returns an array of values in between, but not including, the slashes. then, since what's returned by split() is an array, we can use pop() to pop off the last item and return it.

Upvotes: 16

jfriend00
jfriend00

Reputation: 708036

To make it a little more robust and allow for the possible presence of a trailing slash, hash tags or query parameters on the URL:

function getImageDirectoryByFullURL(url){
    url = url.replace(/#[^#]+$/, "").replace(/\?[^\?]+$/, "").replace(/\/$/, "");
    return url.substr(url.lastIndexOf("/") + 1);
}

And a working demo with a bunch of test cases: http://jsfiddle.net/jfriend00/akVVf/

Upvotes: 3

Elliot Bonneville
Elliot Bonneville

Reputation: 53361

In this case, substr() might be faster than split(). Not 100% sure.

function getImageDirectoryByFullURL(url){
    return url.substr(url.lastIndexOf("/")+1);
}

Edit: I forgot, you don't need to include the extra length parameter. Without passing that in you just get a substr to the end of the string, which is what is desired. While this solution is admittedly a little uglier than Joseph's answer, it is twice as fast in Chrome and something like fives times as fast in Firefox.

Upvotes: 6

Nudier Mena
Nudier Mena

Reputation: 3274

Also you can try something like this, getting the same result.

function getImageUrl( url){
    var result = url.substring(url.lastIndexOf("/") + 1);
    return result;
}

Upvotes: 0

Related Questions