注意:如果这样做.split('.')
,您将错过许多 URL 的基本名称。
您可以找到最后一个正斜杠并提前搜索第一个.
、?
或 &
以#
捕获 URL 的变体。这可能相当于 PHP 的基本名称
function getBaseName(url) {
if(!url || (url && url.length === 0)) {
return "";
}
var index = url.lastIndexOf("/") + 1;
var filenameWithExtension = url.substr(index);
var basename = filenameWithExtension.split(/[.?&#]+/)[0];
// Handle '/mypage/' type paths
if(basename.length === 0) {
url = url.substr(0,index-1);
basename = getBaseName(url);
}
return basename ? basename : "";
}
并像这样使用它
var url = "http://www.example.com/keyword/category.php#4";
var file = getBaseName(url);
结果:
http://www.example.com/keyword/category.php#4 => "category"
http://www.example.com/keyword/category => "category"
http://www.example.com/keyword/category/ => "category"
http://www.example.com/keyword/category?ver=1 => "category"
http://www.example.com/keyword/category/?ver=1 => "category"
http://www.example.com/keyword/category#elem => "category"