Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract end of URL in Javascript?

Tags:

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.
}
like image 486
IAmYourFaja Avatar asked Apr 24 '12 00:04

IAmYourFaja


People also ask

How do I pull the last part of a URL?

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

How do I find a URL path?

To split the URL to get URL path in with JavaScript, we can create a URL instance from the URL string. Then we can use the pathname property to get the URL path. For instance, we write: const url = 'http://www.example.com/foo/path2/path3/path4'; const { pathname } = new URL(url); console.

How do you check if the URL contains a given string in JavaScript?

Use indexOf() to Check if URL Contains a String When a URL contains a string, you can check for the string's existence using the indexOf method from String. prototype. indexOf() . Therefore, the argument of indexOf should be your search string.


2 Answers

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.

like image 66
Joseph Avatar answered Sep 28 '22 19:09

Joseph


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.

like image 25
Elliot Bonneville Avatar answered Sep 28 '22 20:09

Elliot Bonneville