简体   繁体   中英

Get extension from a file url

I am using file(input) to select a file. I want to retrieve the file extension(.jpeg) from a URL C:\Users\Rajat\Pictures\pic1.jpeg . Then after that I want to put the URL into a text box according to their format ie audio, video and image.

Try this:

var url='C:\Users\Rajat\Pictures\pic1.jpeg';
var parts=url.split('.');
console.log(parts[parts.length-1]);

In that case you better go with mimetype instead of extensions.

var fileInput = document.getElementById('your-file-input-id');
var fileType = fileInput.files[0].type;
console.log(fileType);//gives image/jpeg or audio/mp3
var parts = filetype.split('/');
parts[0];//image
parts[1];//jpeg

Using ES2022's Array.at() method (see link for browser support), you can do it in a one liner like so:

 const url = "https://example.com/my-file.jpg"; const extension = url.split(".")?.at(-1); console.log(extension);

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