简体   繁体   中英

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 ?

https://stackoverflow.com/a/423385 provides a partial answer, but does not address the GET parameters.

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

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.

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

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