简体   繁体   中英

How can I extract the filename from a path?

The path from which I want to extract the filename takes the form:

C:\Folder1\Folder2\Folder3\Folder4\Folder5\x.png

This should give x (I do not need the extension). The file is always a PNG file. x can be 1, 2, 3 or 4 digits, but can never contain any other character (only a number).

I tried a 'manual' method, which is working well.

function getId(x) {
  x = x.slice(0,-4);
  var str = "";
  var flag = 0;
  for(var i = x.length - 1; i >= 0; i--) {
    if(!isNaN(x[i])) {
      str = x[i] + str;
      flag = 1;
    } else if(flag == 1) {
      break;
    }
  }
  console.log(str);
}

Is there any simpler approach without using a library?

You could match one or more times a digit in a capturing group. Then match a dot and not a backslash one or more times using a negated character class and assert the end of the string.

(\\d+)\\.[^\\\\]+$

 const regex = /(\\d+)\\.[^\\\\]+$/; const str = "C:\\\\Folder1\\\\Folder2\\\\Folder3\\\\Folder4\\\\Folder5\\\\1.png"; console.log(str.match(regex)[1]); 

You can use split() and pop() to get the file name without extension:

 var file = 'C:\\\\Folder1\\\\Folder2\\\\Folder3\\\\Folder4\\\\Folder5\\\\x.png'; var fileName = file.split(/\\\\/).pop(); fileName = fileName.split('.')[0]; console.log(fileName); 

Not the best way, but so simple:

const str = 'C:\\Folder1\\Folder2\\Folder3\\Folder4\\Folder5\\t.png';
const getId = path => path.split('\\').pop().split('.')[0];
console.log(getId(str));

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