Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match the URL last part with JavaScript

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?

like image 200
KodeFor.Me Avatar asked Feb 29 '12 07:02

KodeFor.Me


2 Answers

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.

like image 87
Koushik Das Avatar answered Oct 21 '22 08:10

Koushik Das


The following regular expression will work:

/[^\/]+$/
like image 26
Alan Haggai Alavi Avatar answered Oct 21 '22 08:10

Alan Haggai Alavi