Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92397

Regexp get last part of url without parameters if they exists

I looking for regular expression to use in my javascript code, which give me last part of url without parameters if they exists - here is example - with and without parameters:

https://scontent-fra3-1.xx.fbcdn.net/v/t1.0-9/14238253_132683573850463_7287992614234853254_n.jpg?oh=fdbf6800f33876a86ed17835cfce8e3b&oe=599548AC

https://scontent-fra3-1.xx.fbcdn.net/v/t1.0-9/14238253_132683573850463_7287992614234853254_n.jpg

In both cases as result I want to get:

14238253_132683573850463_7287992614234853254_n.jpg

Upvotes: 2

Views: 2217

Answers (2)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92397

Here is this regexp

.*\/([^?]+)

and JS code:

let lastUrlPart = /.*\/([^?]+)/.exec(url)[1];

let lastUrlPart = url => /.*\/([^?]+)/.exec(url)[1];



// TEST

let t1 = "https://scontent-fra3-1.xx.fbcdn.net/v/t1.0-9/14238253_132683573850463_7287992614234853254_n.jpg?oh=fdbf6800f33876a86ed17835cfce8e3b&oe=599548AC"

let t2 = "https://scontent-fra3-1.xx.fbcdn.net/v/t1.0-9/14238253_132683573850463_7287992614234853254_n.jpg"

console.log(lastUrlPart(t1));
console.log(lastUrlPart(t2));

May be there are better alternatives?

Upvotes: 6

bnjc
bnjc

Reputation: 56

You could always try doing it without regex. Split the URL by "/" and then parse out the last part of the URL.

var urlPart = url.split("/");
var img = urlPart[urlPart.length-1].split("?")[0];

That should get everything after the last "/" and before the first "?".

Upvotes: 1

Related Questions