打开没有最后路径的当前URL

时间:2017-03-25 22:42:06

标签: javascript

如果我点击链接,页面应加载时不会显示当前网址的最后一条路径。

www.test.com/category/question/test /

www.test.com/category/question /

<a href="javascript:jumpback()"></a>


function jumpback() {
}

怎么可能这样做。我知道有类似的问题,但答案无法帮助我。

4 个答案:

答案 0 :(得分:2)

如果您不想,则不必使用正则表达式删除路径的最后部分:

  function jumpback() {
    var pathArr = window.location.pathname.split('/'); //break the path string to parts
    var lastPart = pathArr.pop(); //remove the last part
    if (lastPart === '') {
      pathArr.pop(); //if the lastPart is an empty string it might be trailing slash, so we need to remove one more part
    }
    window.location.pathname = pathArr.join('/'); //join all remaining parts together and update the pathname, updating pathname forces change in browser, so it emulates clicking on a link
    return false; //To prevent the default click
  }

答案 1 :(得分:1)

您可以尝试手动剥离网址:

function jumpback(){
    var url = top.location.href;
    var lIdx = url.lastIndexOf("/");
    top.location.href = url.substr(0, lIdx);
}

但是,此解决方案忽略了可能跟随url的任何内容,例如GET参数,它也不会考虑这些情况,其中url中没有斜杠(因为你在文档根目录中)< / p>

如果您想要删除网址的其他部分(例如查询参数),您可能需要采取更长的方法:

function jumpback(){
    var url = top.location.href;
    // cut everything from the first "?" if any
    var lIdx = url.lastIndexOf("?");
    if (lIdx >= 0)
        url = substr(0, lIdx-1);


    lIdx = url.lastIndexOf("/");
    //if the url ends with a slash (or multiples of them)
    while (lIdx == url.length){
        // ignore it
        lIdx = url.substr(0, lIdx-1);
        lIdx = url.lastIndexOf("/");
    }
    if (lIdx >= 0)
        top.location.href = url.substr(0, lIdx);
    // otherwise there is no parent directory and you are on the doc root
}

另一种方法是将您的网址拆分为零件并忽略最后一部分:

function jumpback(){
    var url = top.location.href;
    // cut everything from the first "?" if any
    var lIdx = url.lastIndexOf("?");
    if (lIdx >= 0)
        url = substr(0, lIdx-1);

    var urlParts = url.split("/");
    while(urlParts.length > 1 && urlParts[urlParts.length-1] == "")
        urlParts.splice(urlParts.length-1, 1);
    top.location.href = urlParts.join("/");
}

答案 2 :(得分:1)

答案很简单:

window.location.pathname = window.location.pathname.replace(/\/[^\/]+\/?$/,"/");

您提到的路径位于window.location.pathname。你想要的是剥离它的最后一部分,所以只是在最后一个斜杠之后替换内容(如果最后一个字符是斜线,则替换最后一个)。

来自MDN

  

Location接口表示与其链接的对象的位置(URL)。对其进行的更改将反映在与其相关的对象上。

更复杂的版本

function jumpback() {
    var path = window.location.pathname.replace(/\/[^\/]+\/?$/, "/");
    if (path !== window.location.pathname) {
        window.location.pathname = path;
    }
}

答案 3 :(得分:0)

要扩展其他答案,但为了保持简单和可读性,您仍然可以提供以下内容:

function jumpback(){
   var url = top.location.href;
   url = url.substring(0, str.length - 1); //incase there is a '/' at the end

   var lastIndex = url.lastIndexOf("/");
   top.location.href = url.substr(0, lastIndex);
}
相关问题