【问题标题】:Getting just the filename from a path with JavaScript使用 JavaScript 从路径中获取文件名
【发布时间】:2011-02-01 08:01:59
【问题描述】:

我有一个图像的完整路径,我正在使用 jQuery 来读取它:

$('img.my_image').attr('src');

但是我只想要 filename 部分(即没有完整路径)。

是否有任何内置函数可以做到这一点,或者 regex 是唯一的选择吗?

【问题讨论】:

标签: javascript jquery html path


【解决方案1】:
var fileNameIndex = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(fileNameIndex);

【讨论】:

  • 不适用于linux和mac你需要拆分(\和/);
  • 如果您需要跨平台解决方案,RubbelDeCatc's answer bellows 适用于正斜杠和反斜杠。
【解决方案2】:
function getFileName(path) {
return path.match(/[-_\w]+[.][\w]+$/i)[0];
}

【讨论】:

    【解决方案3】:

    在 Javascript 中你可以这样做

    function getFileNameFromPath(path) {
      var ary = path.split("/");
      return ary[ary.length - 1];
    }
    

    【讨论】:

      【解决方案4】:
      var Filename= path.split('/').pop()
      

      【讨论】:

      • 在我看来,这比公认的答案要好。
      • 我觉得应该是这样的 var Filename=path.split('\\').pop();它测试了上面的代码,它不适用于 IE 和智能手机
      • @Moe 路径分隔符因平台而异。
      • 最佳答案!跨平台兼容性
      【解决方案5】:

      我找到了一个更好的版本来处理 unix 和类似 windows 的路径字符串。

      第一名:

      var unix_path = '/tmp/images/cat.jpg';
      console.log(unix_path.replace(/^.*[\\\/]/, ''));
      
      var win_path = 'c:\\temp\images\cat.jpg';
      console.log(win_path.replace(/^.*[\\\/]/, ''));
      

      输出将是 cat.jpg

      第二个:(可能更快)

      var unix_path = '/tmp/images/cat.jpg';
      console.log(unix_path.split(/[\\\/]/).pop());
      
      var win_path = 'c:\\temp\images\cat.jpg';
      console.log(win_path.split(/[\\\/]/).pop());
      

      输出将是 cat.jpg

      【讨论】:

      • 第一种方法将完整路径连接到单个字符串,Windows 路径不使用斜线。
      • @ManuM 使用字符串文字测试这些时,您必须在字符串中使用双反斜杠,例如var win_path = 'c:\\temp\\images\\cat.jpg';。否则它们不会被 JavaScript 解释为反斜杠。
      • 对不起,我从来没有用windows测试过,但是windows路径的双bs问题可能是由正则表达式中的三个反斜杠(\\)引起的。
      【解决方案6】:

      使用此解决方案,您可以获得两个名称,即带和不带文件扩展名。

      //获取图片源 var path=$('img.my_image').attr('src'); //分割url并获取带有文件扩展名的文件名 var file=path.split('/').pop(); //删除扩展名,只保留文件名 var filename=file.split('.').shift();

      【讨论】:

        【解决方案7】:

        除了接受的答案。看起来这是最快的跨平台(Unix 和 Windows)解决方案:

        function basePath(path) {
          return path.substr(
            Math.max(
              path.lastIndexOf('\\'),
              path.lastIndexOf('/'),
            ) + 1,
          );
        }
        

        当您同时拥有来自 Unix 和 Windows 的数据并且我们必须在一个地方解析时,这是必要的。

        这个函数只接受所有可能的分隔符中的最后一个,并在最后一个分隔符之后返回字符串。使用大字符串会更快,这就是为什么:

        • 没有正则表达式,它们比简单相等要慢
        • 没有规范化,没有无条件地扔掉整个字符串并从中创造新的东西
        • 不创建任何新实例,例如新数组等,这需要一些时间和内存
        • 没有额外的循环甚至查找,因为我们在这里不使用数组

        在 Chromex87 中测试:

        // Test subjects
        //=====================
        function basePathUnix(path) {
          return path.split('/').pop();
        }
        
        function basePathUnix2(path) {
          const arr = path.split('/');
          return arr[ arr.length - 1 ];
        }
        
        function basePathUnix3(path) {
          return path.substr(path.lastIndexOf('/') + 1);
        }
        
        function basePathCrossPlatform(path) {
          return path.replace(/^.*[\\\/]/, '');
        }
        
        function basePathCrossPlatform2(path) {
          return path.split(/[\\\/]/).pop();
        }
        
        function basePathCrossPlatform3(path) {
          return path.substr(Math.max(path.lastIndexOf('\\'), path.lastIndexOf('/')) + 1);
        }
        
        function basePathCrossPlatform4(path, separators = ['/', '\\']) {
          return path.substr(Math.max(...separators.map(s => path.lastIndexOf(s))) + 1);
        }
        
        // Tests
        //=====================
        function measureTime(name, fn) {
          const start = window.performance.now();
          for (let i = 0; i < 10000; i++) {
            fn();
          }
          const time = window.performance.now() - start;
        
          console.log(name, time);
        }
        
        function testResults(name, path) {
          console.log('\n[CHECK RESULTS]', name);
        
          console.log('basePathUnix:\t\t', basePathUnix(path));
          console.log('basePathUnix2:\t\t', basePathUnix2(path));
          console.log('basePathUnix3:\t\t', basePathUnix3(path));
          console.log('basePathCrossPlatform:\t', basePathCrossPlatform(path));
          console.log('basePathCrossPlatform2:\t', basePathCrossPlatform2(path));
          console.log('basePathCrossPlatform3:\t', basePathCrossPlatform3(path));
          console.log('basePathCrossPlatform4:\t', basePathCrossPlatform4(path));
        }
        
        function testPerformance(name, path) {
          console.log('\n[MEASURE PERFORMANCE]', name);
        
          measureTime('basePathUnix:\t\t', () => basePathUnix(path));
          measureTime('basePathUnix2:\t\t', () => basePathUnix2(path));
          measureTime('basePathUnix3:\t\t', () => basePathUnix3(path));
          measureTime('basePathCrossPlatform:\t', () => basePathCrossPlatform(path));
          measureTime('basePathCrossPlatform2:\t', () => basePathCrossPlatform2(path));
          measureTime('basePathCrossPlatform3:\t', () => basePathCrossPlatform3(path));
          measureTime('basePathCrossPlatform4:\t', () => basePathCrossPlatform4(path));
        }
        
        function runTest(name, path) {
          setTimeout(() => {
            testResults(name, path);
        
            setTimeout(() => {
              testPerformance(name, path);
            }, 200);
          }, 200);
        }
        
        // Run tests
        //=====================
        setTimeout(() => {
          const pathUnix = '/some/path/string/some/path/string/some/path/string/some/path/string/some/path/string/some/path/file-name';
          runTest('UNIX', pathUnix);
        }, 1000);
        
        setTimeout(() => {
          const pathWind = '\\some\\path\\string\\some\\path\\string\\some\\path\\string\\some\\path\\string\\some\\path\\file-name';
          runTest('WINDOWS', pathWind);
        }, 2000);

        【讨论】:

          猜你喜欢
          • 2010-09-30
          • 2011-11-16
          • 2012-01-21
          • 2012-10-25
          • 2023-03-26
          • 1970-01-01
          • 1970-01-01
          • 2015-04-22
          相关资源
          最近更新 更多