Obasi Obeny Oj Obasi Obeny Oj - 3 months ago 9
Javascript Question

Is it possible to get this part of a string

I wonder if it's possible to get this part of a string.
Here is my string:

var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";


Now I want to be able to grab just this part of the string, the file name:

12391381_10205760647243398_2385261683139818614_n.jpg


I tried:

var result = /[^/]*$/.exec(""+url+"")[0];


, but it will return

user%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=4c92c4d7-8979-4478-a63d-ea190bec87cf


My Regex is wrong.

Another this is, the file extension can be .png or jpg so it's not fixed to jpg.

Answer

Note that may have to be adapted depending on how much the URL string changes:

var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";

var out = string.split('?')[0].split('%2F')[2];

console.log(out); // "12391381_10205760647243398_2385261683139818614_n.jpg"

Comments