如何使用JavaScript/jQuery从URL中提取文件名?

39

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

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

目录结构也是任意的。因此,基本上给定上述任意一个URL(具有任意的目录结构),我需要提取“filename.gif”。提前感谢。


2
请参考可能的重复问题:如何使用JavaScript从完整路径获取文件名? - Bergi
16个回答

1
    var pathnameArray = window.location.pathname.split("/");
    var nameOfFile = pathnameArray[pathnameArray.length -1];

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


1

谢谢Sam Deng,看起来可以用,但是你有一个错别字,我的朋友:

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

谢谢你的帮助,但是你应该将这个作为评论留在相关答案下面,而不是发表一个新的回答(未来你可以建议编辑别人的答案)。 - Luca

1
var filename = /[^\\\/:*?"<>|\r\n]+$/i.exec(window.location.href)[0];

1
我通过以下方式解决了这个问题:

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

0
如果您的URL是这样的:

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;

0

我的答案处理了一些边缘情况,例如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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接