简体   繁体   English

如何从路径中提取文件名?

[英]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). 这应该给x(我不需要扩展名)。 The file is always a PNG file. 该文件始终是PNG文件。 x can be 1, 2, 3 or 4 digits, but can never contain any other character (only a number). x可以是1、2、3或4位数字,但不能包含任何其他字符(只能是数字)。

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: 您可以使用split()pop()获得不带扩展名的文件名:

 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));

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

相关问题 如何在Express Node.js上提取路由名称(路径)(在通话期间,从请求中) - How can I extract the route name (path) on express nodejs (during the call, from the req) 如何在JavaScript中提取当前文档路径的URL的文件名? - How to extract the filename of the URL of the current document path in JavaScript? 如何使用 javascript 提取并更改 url 路径? - How can I extract and then change the url path using javascript? 如何从只有 JS 的路径中删除文件名? - How to remove filename from a path with only JS? 如何从多输入中的FileReader函数中获取文件名? - How can I get the filename from the FileReader function in a Multiple Input? 如何显示来自 GitHub API 的文件名? - How can I display the filename from GitHub API? 如何使用meteor和collectionfs文件系统为我的文件指定路径和文件名 - How can I specify a path and filename for my files with meteor and collectionfs filesystem 如何从url中提取id? - How can I extract the id from the url? "Javascript - 如何从文件输入控件中提取文件名" - Javascript - How to extract filename from a file input control 如何从具有特殊字符的文件名中提取ext-javascript - How to extract an ext from a filename having special chars in it-javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM