【问题标题】:How do I remove get variables and filename from URL using javascript/jquery?如何使用 javascript/jquery 从 URL 中删除获取变量和文件名?
【发布时间】:2012-02-27 01:01:50
【问题描述】:

我正在研究这个问题,但我找不到任何可靠的答案来解决这个特定的目的。假设我有一个网址...

http://mysite.com/stuff/index.php?search=my+search

我怎样才能获取这个 URL 并从中删除 index.php?search=my+search 所以它只是 http://mysite.com/stuff/ ?基本上我只想获取没有文件名的父 URL 或获取变量......无论 URL 是什么(所以我不必为我想要使用它的每个页面自定义函数)

再举一个例子,如果只是……

http://mysite.com/silly.php?hello=ahoy

我只想返回http://mysite.com的根

谁能帮我解决这个问题?我完全迷路了。

【问题讨论】:

    标签: javascript jquery regex url variables


    【解决方案1】:

    尝试使用lastIndexOf("/")

    var url = "http://mysite.com/stuff/index.php?search=my+search";
    url = url.substring(0, url.lastIndexOf("/") + 1);
    alert(url); // it will be "http://mysite.com/stuff/"
    

    var url = "http://mysite.com/silly.php?hello=ahoy";
    url = url.substring(0, url.lastIndexOf("/") + 1);
    alert(url); // it will be "http://mysite.com/"
    

    【讨论】:

    • 谢谢,我想我现在会一直使用 lastIndexOf。
    • console.log(url) 比警报好得多。
    【解决方案2】:

    如果你的网址在str:

    newstr = str.replace(/\/[^\/]+$/,"");
    

    newstr 现在包含直到但不包括字符串中最后一个/ 的路径。要保留最终的/,请使用:

    newstr = str.replace(/\/[^\/]+$/,"/");
    

    【讨论】:

      【解决方案3】:

      在“/”上拆分,丢弃最后一块,将它们重新连接起来,添加尾部斜杠。

      var path = location.href.split('/');
      path.pop();
      path = path.join("/") + "/";
      

      【讨论】:

        【解决方案4】:

        您正在寻找location.hostlocation.hostname。但是您想从完整的字符串中提取它们而不是从当前 URL 中提取它们吗?

        我再次阅读了这个问题,您似乎想要获得包含以下内容的字符串:

        location.protocol + "//" + location.host + location.pathname
        

        对吗?

        【讨论】:

        • location.pathname 将包含index.php
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-21
        • 2011-09-14
        • 2012-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多