Home » Javascript » select a file without specifying the extension in javascript

select a file without specifying the extension in javascript

Posted by: admin November 1, 2017 Leave a comment


I have a folder with thumbnails. These can be .jpg or .gif or .png etc.
How can I select a file with only the name using javascript?

For example if there is a file called tree.jpg I want to find it with only using tree. The folder in which these thumbnails are located is always the same. Below is the code snippet I’m using. My question is about the line with var src. In that line I want to find the file in the folder thumbnails with only using the name.

(projects is a json file)
function buildWork(projects) {
 var container = document.getElementById('projects');
 var row = document.createElement('div');
 row.className = 'row no-gutters';

for(var i in projects) {
  col = document.createElement('div');
  col.className = 'col-6 col-md-4 item thumbnail';

  var src = "thumbnails/" + project.name;

  col.innerHTML = '<img src='+ src +'></img>';



In-browser JavaScript isn’t permitted to list files on your harddrive. If you want to try several known file extensions against a server‘s filesystem, you can use this:

const fname = "tree";
const exts = ['.png', '.jpg', ... ];

let queries = exts.map(ext => fetch(`${fname}${ext}`).then(response));

Promise.all(queries).then(responses => {
    // Only one response will return "ok":
    // It will be at the same index as the correct extension
    // in the `exts` array.

    // This will hold the extension of the FIRST extension that returns
    // from the server successfully:
    let correctExtension = exts[responses.map(r => r.ok).indexOf(true)];

    let trueFileName = fname + correctExtension;

[EDIT] This method should still work for your updated question; however, you’re still requesting every file from the server and hoping one of them exists. (The trueFileName var will hold tree.jpg at the end, provided that this file exists on the server.)

Your other option is to use API-style redirects on your HTTP server; but that’s a whole different story and has no effect on your JavaScript.