代码之家  ›  专栏  ›  技术社区  ›  Wais Kamal

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

  •  -1
  • Wais Kamal  · 技术社区  · 7 年前

    我要从中提取文件名的路径的格式为:

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

    这应该给出x(我不需要扩展名)。该文件始终是PNG文件。x可以是1、2、3或4位数字,但不能包含任何其他字符(只有数字)。

    我尝试了一种“手动”方法,效果很好。

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

    在不使用库的情况下有没有更简单的方法?

    3 回复  |  直到 7 年前
        1
  •  3
  •   The fourth bird    7 年前

    您可以在一个捕获组中匹配一个或多个数字。然后匹配一个点而不是反斜杠一次或多次使用否定 character class 并断言字符串的结尾。

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

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

    你可以用 split() pop() 要获取不带扩展名的文件名:

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

    不是最好的方法,但很简单:

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