【问题标题】:How to extract a file name from an URI in javascript?如何从javascript中的URI中提取文件名?
【发布时间】:2021-08-13 15:07:46
【问题描述】:
我有一个这样的网址 -
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
其中我需要获取文件名。在这种情况下,
85fd93fa-1ca7-4055-b6d3-6a41db4s498b-testcup1.png
我尝试使用其他答案中建议的正则表达式,但我无法编写复杂的表达式。
我尝试使用JavaScripts Good parts by Coderholic,但它并没有给我想要的东西。我从那里找到了一个通用正则表达式,我将其粘贴在下面
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]);
}
但是上面的代码 sn-p 给了我这样的输出。
/v0/b/sathyatest12-blog.appspot.com/o/85fa93fa-1ca7-4055-b6b3-6a41db4s498b-testcup1.png
请指导我如何实现以下结果
85fa93fa-1ca7-4055-b6b3-6a41db4s498b-testcup1.png
【问题讨论】:
标签:
javascript
regex
url
uri
【解决方案1】:
为什么不简单地使用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}`)
【解决方案2】:
我已经解决了这个问题,如下所示
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);
我已经在 jsfiddle.net 上测试过了
【解决方案3】:
您也可以先反转字符串,因为我们无法使用正则表达式找到/ 的最后一个索引。但是如果我们可以反转字符串,我们可以找到?的第一个索引。
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);
}