简体   繁体   中英

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

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?

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 "?".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM