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?

KodeFor.Me
  • 13,069
  • 27
  • 98
  • 166
  • 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 http://medialize.github.com/URI.js – Jim Blackler Feb 29 '12 at 07:50

6 Answers6

26

Take a look at the lastIndexOf method:

var index = url.lastIndexOf("/");
var fileName = url.substr(index)
Matthias
  • 12,053
  • 4
  • 49
  • 91
  • This is better then all above. – shift66 Feb 29 '12 at 07:56
  • 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) – tbraun Mar 05 '14 at 16:31
  • See http://stackoverflow.com/a/11664379/232175 for a nice library which handles more complex URIs (URI.js). – Matthias Mar 07 '14 at 12:49
13

The following regular expression will work:

/[^\/]+$/
Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
3

Use this Regex:-

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

Get file name using $6

Siva Charan
  • 17,940
  • 9
  • 60
  • 95
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.

Koushik Das
  • 9,678
  • 3
  • 51
  • 50
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)

shift66
  • 11,760
  • 13
  • 50
  • 83
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
Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73