I have an URL like this -
https://firebasestorage.googleapis.com/v0/b/sathyatest12-blog.appspot.com/o/85fa93fa-1ca7-4055-b6b3-6a41db4s498b-testcup1.png?alt=media&token=4dfd3ca0-a55b-4052-956c-94a2bs13c77e
of which I need to get the file name. In this case,
85fd93fa-1ca7-4055-b6d3-6a41db4s498b-testcup1.png
I tried using regex as suggested in other answers but I am unable to write complicated expressions.
I tried using JavaScripts Good parts by Coderholic but it is not giving me what I want. I found a generic regex from there which I am pasting below
var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/; var url = 'http://www.ora.com:80/goodparts?q#fragment'; var result = parse_url.exec(url); var names = ['url', 'scheme', 'slash', 'host', 'port', 'path', 'query', 'hash']; var blanks = ' '; var i; for (i = 0; i < names.length; i += 1) { document.writeln(names[i] + ':' + blanks.substring(names[i].length), result[i]); }
But this is giving me
/v0/b/sathyatest12-blog.appspot.com/o/85fa93fa-1ca7-4055-b6b3-6a41db4s498b-testcup1.png
Please help.
Why not simply use the URL API ?
var URL_val = 'https://firebasestorage.googleapis.com/v0/b/sathyatest12-blog.appspot.com/o/85fa93fa-1ca7-4055-b6b3-6a41db4s498b-testcup1.png?alt=media&token=4dfd3ca0-a55b-4052-956c-94a2bs13c77e', URL_Obj = new URL(URL_val); let lastOne = URL_Obj.pathname.split('/').pop() console.log(`lastOne: ${lastOne}`)
I have solved this problem simply like below
var url_string = "https://firebasestorage.googleapis.com/v0/b/sathyatest12-blog.appspot.com/o/85fa93fa-1ca7-4055-b6b3-6a41db4s498b-testcup1.png?alt=media&token=4dfd3ca0-a55b-4052-956c-94a2bs13c77e"; //window.location.href
firstPos = url_string.lastIndexOf('/');
lastPos = url_string.indexOf('?');
var result = url_string.slice(firstPos+1, lastPos);
console.log(result);
I have tested this on jsfiddle.net
You can also achieve the same result first to reverse the string since we cannot find the last index of /
using regex. But we can find the first index of ?
if we can reverse the string.
const str = "https://firebasestorage.googleapis.com/v0/b/sathyatest12-blog.appspot.com/o/85fa93fa-1ca7-4055-b6b3-6a41db4s498b-testcup1.png?alt=media&token=4dfd3ca0-a55b-4052-956c-94a2bs13c77e"; const reverse = str.split("").reverse().join(""); const regex = /(?<=\?)(.*?)\//; const match = reverse.match(regex); if (match) { const result = match[1].split("").reverse().join(""); console.log(result); }
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.