问题
I have a URL:-
http://www.example.com/keyword/category.php
or
http://www.example.com/keyword/category.php#4
I need a magic abracadabra which gives me only the pagename as category from this URL.
Here is what I tried, and it gives category.php. But it has two problems. It is ugly and long and it gives me filename with an extension.
var currurl = window.location.pathname;
var index = currurl.lastIndexOf("/") + 1;
var filename = currurl.substr(index);
Thanks.
回答1:
Just make this into a function as below:
function getPageName(url) {
var index = url.lastIndexOf("/") + 1;
var filenameWithExtension = url.substr(index);
var filename = filenameWithExtension.split(".")[0]; // <-- added this line
return filename; // <-- added this line
}
Then when you need to use it:
var url = "http://www.example.com/keyword/category.php";
var myFilename = getPageName(url);
All of the "ugliness" has been hidden in a function and the main code looks nice and clean!
回答2:
function getPageName() {
var index = window.location.href.lastIndexOf("/") + 1,
filenameWithExtension = window.location.href.substr(index),
filename = filenameWithExtension.split(".")[0];
return filename;
}
回答3:
For work with querystring like http://www.example.com/keyword/category.php?parametro=teste
function getPageName(url) {
var index = url.lastIndexOf("/") + 1;
var filenameWithExtension = url.substr(index);
var filename = filenameWithExtension.split(".")[0];
filename = filename.split("?")[0]; // <-- added this line
return filename;
}
回答4:
Note: If you do .split('.')
, you will miss the base names of many URLs.
You can find the last forward slash and search ahead for the first .
, ?
, &
or #
to catch variations of URLs. This is probably the equivalent of PHP's basename
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 : "";
}
and use it like so
var url = "http://www.example.com/keyword/category.php#4";
var file = getBaseName(url);
Results:
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"
JSBin demo
来源:https://stackoverflow.com/questions/16286384/how-to-get-the-pagename-from-the-url-without-the-extension-through-jquery