【问题标题】:How to get url path without $_GET parameters using javascript?如何使用 javascript 获取没有 $_GET 参数的 url 路径?
【发布时间】:2013-08-15 21:46:47
【问题描述】:

如果我当前的页面是这种格式...

http://www.mydomain.com/folder/mypage.php?param=value

有没有简单的方法来获得这个

http://www.mydomain.com/folder/mypage.php

使用javascript?

【问题讨论】:

    标签: javascript jquery url


    【解决方案1】:

    尽量用split点赞

    var url = "http://www.mydomain.com/folder/mypage.php?param=value";
    var url_array = url.split("?");
    alert(url_array[0]);    //Alerts http://www.mydomain.com/folder/mypage.php
    

    即使GET 中有很多参数,第一段将是没有GET 参数的URL

    这是DEMO

    【讨论】:

    • 谢谢,正是我需要的!我没有在问题中提到它,但是当没有传递参数时这也有效=)
    • 您的基于字符串的解决方案将如何处理格式错误的 URL,例如 http://www.domain.com/page#anchor?parameter ?使用文档对象及其 api 是一个更强大的解决方案 IMO
    【解决方案2】:

    试试

    var result = yourUrl.substring(0, yourUrl.indexOf('?'));
    

    Working demo

    【讨论】:

      【解决方案3】:

      不要做这个正则表达式和拆分东西。使用浏览器内置的 URL 解析器。

      window.location.origin + window.location.pathname
      

      如果您需要解析不是当前页面的 URL:

      var url = document.createElement('a');
      url.href = "http://www.example.com/some/path?name=value#anchor";
      console.log(url.origin + url.pathname);
      

      并且支持IE(因为IE没有location.origin):

      location.protocol + '//' + location.host + location.pathname;
      

      (灵感来自https://stackoverflow.com/a/6168370/711902

      【讨论】:

      【解决方案4】:
      var options = decodeURIComponent(window.location.search.slice(1))
           .split('&')
           .reduce(function _reduce (/*Object*/ a, /*String*/ b) {
           b = b.split('=');
           a[b[0]] = b[1];
           return a;
         }, {});
      

      【讨论】:

        【解决方案5】:

        试试这个:

        var url=document.location.href;
        var mainurl=url.split("?");
        alert(mainurl[0]);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-15
          • 2018-11-13
          • 1970-01-01
          • 2018-09-09
          • 2011-05-28
          • 1970-01-01
          • 1970-01-01
          • 2023-03-13
          相关资源
          最近更新 更多