如何通过JQuery从没有扩展名的URL获取页面名称 [英] How to get the pagename from the URL without the extension through JQuery
本文介绍了如何通过JQuery从没有扩展名的URL获取页面名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个网址: -
I have a URL:-
http://www.example.com/keyword/category.php
或
http://www.example.com/keyword/category.php#4
我需要一个神奇的abracadabra,它只给我这个网址中的类别页面名称。
I need a magic abracadabra which gives me only the pagename as category from this URL.
这是我尝试过的,它给出了类别.PHP 即可。但它有两个问题。这是丑陋和漫长的,它给我带有扩展名的文件名。
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);
谢谢。
推荐答案
只需将其转换为如下函数:
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!
这篇关于如何通过JQuery从没有扩展名的URL获取页面名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文