11

I have some URLs and I like to catch the final part of the url.

My URLs are in the form of

http://www.my-site.dch/wp-content/uploads/2012/02/Tulips.jpg
http://www.my-site.dch/wp-content/uploads/2012/02/Tulips-150x200.jpg
http://www.my-site.dch/wp-content/uploads/2012/02/Tulips-500x350.jpg

and what I like to catch is the /Tulips.......jpg

I have try that but with no luck

\/.*(-\d+x\d+)\.(jp(e)?g|png|gif)

Any better idea?

1
  • 1
    If you have to a lot of ULR manipulation and you'd like your code to be more readable, I recommend the excellent uri.js medialize.github.com/URI.js Commented Feb 29, 2012 at 7:50

6 Answers 6

26

Take a look at the lastIndexOf method:

var index = url.lastIndexOf("/");
var fileName = url.substr(index)
Sign up to request clarification or add additional context in comments.

3 Comments

This is better then all above.
heads up, this solution does not work if url has parameters. i.e.: www.something.com/image.jpg?size=100x100 (upvoted because it is still a good solution for this question)
See stackoverflow.com/a/11664379/232175 for a nice library which handles more complex URIs (URI.js).
13

The following regular expression will work:

/[^\/]+$/

1 Comment

This picks up the query string as well.
3

Use this Regex:-

^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$

Get file name using $6

Comments

1

.*/(.*) use this pattern and get the group 1.it will work I guess.
.* is a greedy regex so it will match until the last slash. After that in group 1 will be the last characters (what you need)

1 Comment

I think @winSharp93's answer is the best.
1

If you are sure that all the images are jpg:

/.\/\S+\.jpg/

Otherwise, more generale:

/.\/\S+\.\w{2,3}/

That is:

. any char
\/ the slash before the file name
\S+ any non blank char to match the file name (at least one)
\. the file extension separator
jpg or \w{3,4} the file extension

Comments

1

In case you came here looking to find the last part of the url even if the url ends with / There's a solution which is simpler than any regex solution. Even though the question is regarding regex, I will add it because it does add some value here.

If the url was this http://www.my-site.dch/wp-content/uploads/2012/02/Tulips.jpg

const url = 'http://www.my-site.dch/wp-content/uploads/2012/02/Tulips.jpg'
const lastpart = url.split('/').filter(e => e).pop() 

In this case, the last part would return the last part even if it ends with / So, if you had a url like this

/services/mosquito-control/

and you wanted to catch mosquito-control, you would be do it with this.

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.