调用URL的一部分

时间:2018-05-21 14:35:48

标签: javascript html

下面的代码正在为我工​​作

<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;

谢谢,

3 个答案:

答案 0 :(得分:1)

是。使用 .substr() .lastIndexOf() 的简单字符串操作方法:

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:0)

它是一个子串基本操作。

步骤是:

  1. 使用您已完成的行获取您的网址
  2. 查找/
  3. 的最后一次出现的索引
  4. 将字符串从0串接字到

    之前的索引

    &#13;
    &#13;
        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;
    &#13;
    &#13;

答案 2 :(得分:0)

您应该使用window.location.hostname代替window.location.hrefhostname给出了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();" >