我沒有發現任何答案接近強壯。這是我的解決方案。
function getFileName(url, includeExtension) {
var matches = url && typeof url.match === "function" && url.match(/\/?([^/.]*)\.?([^/]*)$/);
if (!matches)
return null;
if (includeExtension && matches.length > 2 && matches[2]) {
return matches.slice(1).join(".");
}
return matches[1];
}
var url = "http://example.com/index.htm";
var filename = getFileName(url);
// index
filename = getFileName(url, true);
// index.htm
url = "index.htm";
filename = getFileName(url);
// index
filename = getFileName(url, true);
// index.htm
// BGerrissen's examples
url = "http://stackoverflow.com/questions/3671522/regex-capture-filename-from-url-without-file-extention";
filename = getFileName(url);
// regex-capture-filename-from-url-without-file-extention
filename = getFileName(url, true);
// regex-capture-filename-from-url-without-file-extention
url = "http://gunblad3.blogspot.com/2008/05/uri-url-parsing.html";
filename = getFileName(url);
// uri-url-parsing
filename = getFileName(url, true);
// uri-url-parsing.html
// BGerrissen fails
url = "http://gunblad3.blogspot.com/2008/05/uri%20url-parsing.html";
filename = getFileName(url);
// uri%20url-parsing
filename = getFileName(url, true);
// uri%20url-parsing.html
// George Pantazis multiple dots
url = "http://gunblad3.blogspot.com/2008/05/foo.global.js";
filename = getFileName(url);
// foo
filename = getFileName(url, true);
// foo.global.js
// Fringe cases
url = {};
filename = getFileName(url);
// null
url = null;
filename = getFileName(url);
// null
爲了適應原始問題,默認行爲是排除擴展名,但這很容易被顛倒。
如果您需要該測試,請參閱@ BGerrissen的解決方案,此解決方案對包含多個句點的文件名失敗。 – 2012-08-18 02:51:04