某个变量可能包含相对路径或绝对路径。无论哪种情况,我都需要能够从变量中提取文件名:
http://www.somesite.com/dir1/dir2/filename.gif
/dir1/dir2/filename.gif
目录结构也是任意的。因此,基本上给定上述任意一个URL(具有任意的目录结构),我需要提取“filename.gif”。提前感谢。
某个变量可能包含相对路径或绝对路径。无论哪种情况,我都需要能够从变量中提取文件名:
http://www.somesite.com/dir1/dir2/filename.gif
/dir1/dir2/filename.gif
目录结构也是任意的。因此,基本上给定上述任意一个URL(具有任意的目录结构),我需要提取“filename.gif”。提前感谢。
var pathnameArray = window.location.pathname.split("/");
var nameOfFile = pathnameArray[pathnameArray.length -1];
在考虑创建数组与使用其他人提到的 substr 时,可能存在一些我不知道的开销。因此,也许这不是一个很好的答案,而是解决同样问题的不同方法。
谢谢Sam Deng,看起来可以用,但是你有一个错别字,我的朋友:
// Extract filename from current page.
var filePath = window.location.pathname;
var fileName = filePath.substr(filePath.lastIndexOf("/") + 1);
var filename = /[^\\\/:*?"<>|\r\n]+$/i.exec(window.location.href)[0];
var URL = window.location.pathname; // Gets page name
var page = URL.substring(URL.lastIndexOf('/') + 1);
// then display your filename to console
console.info(page)
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;
我的答案处理了一些边缘情况,例如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