下面的代码正在为我工作
<html>
<body>
<input type="button" value="Click Here" border="2" onClick="test();" >
<script>
function test() {alert(window.location.href);}
</script>
</body>
</html>
结果是&#34; file:/// C:/Users/Administrator/Desktop/test.html"有没有办法检索结果为&#34; file:/// C:/ Users / Administrator / Desktop /&#34;
谢谢,
答案 0 :(得分:1)
是。使用 .substr()
和 .lastIndexOf()
的简单字符串操作方法:
var theLocation = "file:///C:/Users/Administrator/Desktop/test.html";
// Get a substring of the original that starts at the beginning of the string
// and ends where the last / is, plus one (to include the / at the end).
var theNewLocation = theLocation.substr(0, theLocation.lastIndexOf("/") + 1);
console.log(theNewLocation);
&#13;
答案 1 :(得分:0)
它是一个子串基本操作。
步骤是:
将字符串从0串接字到
之前的索引
var locationStart = window.location.href;
//for test exemple
locationStart ="file:///C:/Users/Administrator/Desktop/test.html";
var refactoreLocation = locationStart.substr(0, locationStart.lastIndexOf("/")+1);
console.log(refactoreLocation);
&#13;
答案 2 :(得分:0)
您应该使用window.location.hostname
代替window.location.href
。 hostname
给出了server/root folder name
的名称,该文件正在运行。
或者
如果您想获取文件夹名称的路径,如您所说, file:/// C:/ Users / Administrator / Desktop / ,您可以使用以下代码段
var getUrl = window.location;
function test() {
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + base(getUrl.pathname);
alert(baseUrl);
}
function base(b){
var parts = b.split('/');
var i;
var url = '';
for(var i=1; i< parts.length-1; i++) {
url = url + parts[i]+"/";
}
return url;
}
<input type="button" value="Click Here" border="2" onClick="test();" >