---
title: "js 获取当前页面路径"
author: "alanland"
date: "2014-06-04T15:29:56Z"
tags: []
categories: ["Web前端"]
slug: "js"
draft: false
lastmod: "2014-06-04T15:35:42Z"
id: 2075886
url: "https://alanland.iteye.com/blog/2075886"
---

==

// http://xxx/abc/def/abc.html

 

// http://xxx/abc/def/

// -----&gt; /abc/def

alert(location.pathname.substring(0,location.pathname.lastIndexOf('/'))); 

location.pathname.substring(0,location.pathname.lastIndexOf('/'))

==

 

```
//js获取项目根路径，如： http://localhost:8083/uimcardprj
function getRootPath(){
    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath=window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht=curWwwPath.substring(0,pos);
    //获取带"/"的项目名，如：/uimcardprj
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return(localhostPaht+projectName);
}
```

 

 

==

 

```
//获取当前文件全路径
<script language="javascript">
alert(window.location.href);
alert(window.location);
alert(location.href);
alert(parent.location.href);
alert(top.location.href);
alert(document.location.href);
alert(document.URL);
</script>

//获取当前目录方法
<script type="text/javascript">
//方法一
var str = location.href;
var arr = str.split("/");
delete arr[arr.length-1];
var dir = arr.join("/");
alert(dir);

//方法二
alert(location.href.substring(0,location.href.lastIndexOf('/')));
</script>

//获取当前文件名
<script   language=javascript>  
var  filename=location.href;
filename=filename.substr(filename.lastIndexOf('/')+1);  
alert(filename);  
</script>

 
```

 

==