从地址栏获取页面文件名

Get the page file name from the address bar

本文关键字:文件名 获取 地址栏      更新时间:2023-09-26

我想知道是否可以使用jquery或javascript从地址栏获取页面名称。我知道这可以用PHP完成,但我真的不想,因为它只是一个html网站。

。如果地址是www.mywebsite.com/hello.htm,我如何将hello.htm部分从地址中取出。

感谢您提供的帮助

试试这个

location.pathname.substring(location.pathname.lastIndexOf("/") + 1);

location.pathname给出了页面url的部分(不包括域名)。要只获得文件名,您必须使用substring方法提取它。

https://developer.mozilla.org/en/DOM/window.location

alert(location.pathname)

如果不需要前置斜杠,可以去掉它。

location.pathname.substring(1)

当前页:单行查找当前页的文件名听起来更优雅:

location.href.split("/").slice(-1)

location.pathname.split("/").slice(-1)

这是很酷的自定义导航框的链接,所以指向当前的链接是由CSS类启发。

JS:

$('.menu a').each(function() {
    if ($(this).attr('href') == location.href.split("/").slice(-1)){ $(this).addClass('curent_page'); }
});
CSS:

a.current_page { font-size: 2em; color: red; }

试试这个:

var pageName = (function () {
        var a = window.location.href,
            b = a.lastIndexOf("/");
        return a.substr(b + 1);
    }());

Location对象是你的朋友:

var pageName = location.pathname.substring(1);
http://www.w3schools.com/jsref/obj_location.asp

document.URL.match(/[^'/]+$/);


文档。URL返回文档的位置。.match()是一个使用正则表达式过滤字符串的方法。/[^'/]+$/获取从最后一个斜杠/之后开始的字符串的其余部分。

我遇到了一个问题,我需要删除查询字符串参数(?)和/或锚(#)标签。我这样做了:

var path = window.location.pathname.toLowerCase();
// find the end of path prior the Query and Anchor designations. strip off everything after the ? or #.  
//      if the ? is first, then use ?, else use the #, else use the string length.
// then replace all ' with /
// then split it into an array based on /
var pagePathAry = path.substr(0, path.indexOf("?") > -1 && path.indexOf("?") < path.indexOf("#") ? path.indexOf("?") : path.indexOf("#") > -1 ? path.indexOf("#") : path.length).replace("''", "/").split("/");
// get the folder it's in
var subFolder = pagePathAry[pagePathAry.length - 2];
// get the page name
var pageName = pagePathAry[pagePathAry.length - 1];