简体   繁体   English

使用JavaScript从完整路径获取不带GET参数的文件名?

[英]Get the file name without GET parameters from a full path using JavaScript?

Given /foo/bar/image.jpg?x=1&y=2 , how do I obtain image.jpg ? 给定/foo/bar/image.jpg?x=1&y=2 ,如何获取image.jpg

https://stackoverflow.com/a/423385 provides a partial answer, but does not address the GET parameters. https://stackoverflow.com/a/423385提供了部分答案,但未解决GET参数。

You can use regex as others have suggested, but I find this more readable: 您可以按照其他人的建议使用正则表达式,但是我发现这更易读:

var src = '/foo/bar/image.jpg?x=1&y=2';
var img = src.split('/').pop().split('?')[0];
console.log(img);

Since the ? 自从? symbol separates the GET parameters from the URL, you can 符号将GET参数与URL分开,您可以

str=str.split("?")[0]
filename = str.replace(/^.*[\/]/, '')

Try: 尝试:

var str = "/foo/bar/image.jpg?x=1&y=2";
var fileName = str.split('/').slice(-1)[0].split('?')[0];

or, for a regex method: 或者,对于正则表达式方法:

var fileName = str.split('/').slice(-1)[0].match(/[^?]+/)[0];

You can use this regex: 您可以使用此正则表达式:

/\/([^?\/]+(?=\?|$))/

and use captured grpup #1. 并使用捕获的grpup#1。

RegEx Demo 正则演示

/        # matches a literal /
[^?\/]+  # matches 1 or more of any char that is not ? or /
(?=\?|$) # is a lookahead to assert that next position is ? or end of line

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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