【问题标题】:How to pull the file name from a url using javascript/jquery?如何使用 javascript/jquery 从 url 中提取文件名?
【发布时间】:2010-11-21 02:22:48
【问题描述】:

某个变量可能包含相对路径或绝对路径。无论哪种方式,我都需要能够从变量中提取文件名:

http://www.somesite.com/dir1/dir2/filename.gif
/dir1/dir2/filename.gif

目录结构也是任意的。所以基本上给定上面的任何一个url(带有任意目录结构)我需要拉'filename.gif'。提前致谢

【问题讨论】:

标签: javascript jquery regex


【解决方案1】:

我的回答处理 URL 已编码或 URL 包含作为编码 URL 的查询值的边缘情况,其中 / 变为 %2F

const getImageNameFromURL = (urlInput) => {
  const imageFullnameResult = urlInput.match(/.+(\/|%2F)(.+)/);

  if (!imageFullnameResult) return null;

  const imageFullname = imageFullnameResult[2];

  const imageNameResult = imageFullname.match(
    /.+(jpg|png|svg|jpeg|webp|bmp|gif)/
  );

  if (!imageNameResult) return imageFullname;

  const imageName = imageNameResult[0];

  if (!imageName) return null;

  return imageName;
};

// common URL
const commonURL = 'https://static.tvtropes.org/pmwiki/pub/images/aubrey_plaza.jpg?quality=75&w=1200&h=900&crop=1'

// URL contains query which is an encoded URL which is the actual image.
const urlContainsEncodedURL = 'https://ca-times.brightspotcdn.com/dims4/default/a7ccc15/2147483647/strip/true/crop/2048x1152+0+0/resize/840x473!/quality/90/?url=https%3A%2F%2Fcalifornia-times-brightspot.s3.amazonaws.com%2Fd5%2Fb5%2Fa8bffb00214d8bd8149373c18a6a%2Fla-1467703026-snap-photo'

console.log(getImageNameFromURL(commonURL))
// result: aubrey_plaza.jpg


console.log(getImageNameFromURL(urlContainsEncodedURL))
// result: la-1467703026-snap-photo

【讨论】:

    【解决方案2】:

    我通过这个解决了这个问题:

    var URL = window.location.pathname; // Gets page name
    var page = URL.substring(URL.lastIndexOf('/') + 1); 
    // then display your filename to console
    console.info(page)
    

    【讨论】:

      【解决方案3】:
      var filename= url.split('/').pop()
      

      【讨论】:

        【解决方案4】:
            var pathnameArray = window.location.pathname.split("/");
            var nameOfFile = pathnameArray[pathnameArray.length -1];
        

        在考虑创建数组与使用其他人提到的 substr 时,可能存在一些我不知道的开销。所以也许这不是一个很好的答案,而是解决同一问题的不同方法。

        【讨论】:

          【解决方案5】:

          如果你的网址是这样的:

          yourdomain.com/app_dev.php
          yourdomain.com/app_dev.php/article/2
          

          而您只想提取文件名 (/app_dev.php) 以便可以链接到您的主页,请使用:

          var filename = window.location.pathname.substr(0, window.location.pathname.indexOf("/", 1));
          window.location = filename;
          

          【讨论】:

            【解决方案6】:
            var URL = window.location.pathname; // Gets page name
            var page = URL.substring(URL.lastIndexOf('/') + 1);  
            alert(page);
            

            【讨论】:

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

              【讨论】:

              • 这比使用正则表达式快吗?
              • 我收到的是 /filename.gif 而不是 filename.gif。在调用 substr 之前,索引应该增加 1。
              • 使用slice 代替substr: JavaScript: Slice, Substring, or Substr?
              • @Gregoire 如果 / 是 \ 会发生什么,那么您如何获取文件名?
              • @Pomster var index = yourstring.lastIndexOf("\\") + 1;
              【解决方案8】:

              感谢 sam deng,似乎可以工作,但我的朋友你有一个错字:

              // Extract filename from current page.
              var filePath = window.location.pathname;
              var fileName = filePath.substr(filePath.lastIndexOf("/") + 1);
              

              【讨论】:

              • 感谢您的帮助,但您应该将此作为对相关答案的评论,而不是发布新的(将来您将能够建议对其他人的答案进行编辑)
              【解决方案9】:
              var filename = /[^\\\/:*?"<>|\r\n]+$/i.exec(window.location.href)[0];
              

              【讨论】:

                【解决方案10】:

                短途

                var filename = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
                

                【讨论】:

                • 这个不支持filename.php/arctile/slug-name(它会返回slug-name)
                • 当您只检索值时,我建议使用document.URL 代替window.location.href
                【解决方案11】:
                // Extract filename from current page.
                var filePath = window.location.pathname;
                var fileName = filePath.substr(urlPath.lastIndexOf("/") + 1);
                

                【讨论】:

                • 什么是urlPath?它不是变量或窗口属性。
                【解决方案12】:
                var path = window.location.pathname;
                var filename = path.match(/.*\/([^/]+)\.([^?]+)/i)[1];
                

                如果您不希望查询字符串成为文件名的一部分(您可能不希望),请使用此选项。

                【讨论】:

                • 好极了,但是你能不能扩展最后也去掉参数的功能,包括一个“”?谢谢
                • @JamesCazzetta:可能对你的需求有点过分了,但这会从一个 URI 中得到你需要的一切:gist.github.com/1169555
                【解决方案13】:

                对于您的示例,子字符串搜索可能是您的最佳选择。

                但是,如果您的 URI 实际上足够复杂,您可以尝试 Steven Levithan 的 parseUri

                parseUri(uri).file;
                

                它有 2 种模式,每一种都有自己的怪癖,所以一定要check out the demo

                【讨论】:

                  【解决方案14】:
                  var filename = url.match(/.*\/(.*)$/)[1];
                  

                  【讨论】:

                    【解决方案15】:

                    我会使用正则表达式。

                    [^/]*$
                    

                    它选择最后一个斜杠之后的所有内容,直到最后。您可以展开它以单独选择扩展名:

                    /([^/]*?)(\.[^\./]*)?$
                    

                    【讨论】:

                    • 我发现这个正则表达式更清晰,但它不是用 JavaScript 编写的......这是完整的东西:url.match('[^/]*$')[0]
                    【解决方案16】:

                    使用正则表达式,按照这些思路应该可以解决问题:

                    [^/]+\.[^/]+
                    

                    虽然这并不能涵盖所有可能的情况,但它应该非常适合大多数情况。你可以使用这些:

                    var url = window.location.href;
                    var regex = new RegExp("[^/]+\.[^/]+");
                    var fileName = regex.exec(url);
                    

                    希望有帮助

                    【讨论】:

                    • 不。这将导致匹配 ["http:"]
                    猜你喜欢
                    • 1970-01-01
                    • 2011-10-23
                    • 2012-02-27
                    • 2018-09-08
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-05-29
                    • 1970-01-01
                    • 2015-03-19
                    相关资源
                    最近更新 更多