【问题标题】:How to obtain the query string from the current URL with JavaScript?如何使用 JavaScript 从当前 URL 获取查询字符串?
【发布时间】:2012-04-09 20:40:19
【问题描述】:

我有这样的网址:

http://localhost/PMApp/temp.htm?ProjectID=462

我需要做的是获取? 符号(查询字符串)之后的详细信息——即ProjectID=462。如何使用 JavaScript 获得它?

到目前为止我所做的是:

var url = window.location.toString();
url.match(?);

我不知道下一步该做什么。

【问题讨论】:

标签: javascript query-string


【解决方案1】:

看看MDN article关于window.location

QueryString 在window.location.search 中可用。

如果您希望使用更方便的界面,可以使用 URL 界面的 searchParams 属性,该属性返回一个 URLSearchParams 对象。返回的对象有许多方便的方法,包括 get 方法。所以上面例子的等价物是:

let params = (new URL(document.location)).searchParams;
let name = params.get("name");

URLSearchParams 接口也可用于解析查询字符串格式的字符串,并将其转换为方便的 URLSearchParams 对象。

let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);

searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true

URLSearchParams 接口现在在浏览器中被广泛采用(95%+ 根据Can I Use),但如果您确实需要支持旧版浏览器,您可以使用polyfill

【讨论】:

  • 请注意:始终使用encodeURIComponent/decodeURIComponent 而不是escape/unescape
  • 旧版浏览器的第一个函数getQueryStringValue,不适用于?foo=bar&foo1=bar1 如果我们尝试获取foo 的值,它会返回empty string
  • 旧浏览器(IE)可以使用polyfill for URLSearchParams
  • @Pratyush 是的,我在答案中提到了这一点,并参考了更流行和更频繁更新的 url-search-params-polyfill 包。
  • const params = (new URL(url)).searchParams; 为我工作。
【解决方案2】:

使用window.location.search 获取? 之后的所有内容包括?

例子:

var url = window.location.search;
url = url.replace("?", ''); // remove the ?
alert(url); //alerts ProjectID=462 is your case

【讨论】:

  • 或者更简单:let querystring = window.location.search.substring(1);
【解决方案3】:
decodeURI(window.location.search)
  .replace('?', '')
  .split('&')
  .map(param => param.split('='))
  .reduce((values, [ key, value ]) => {
    values[ key ] = value
    return values
  }, {})

【讨论】:

  • 好方法。谢谢。一点点修复它:替换检查整个(!)字符串。我们需要删除第一个字符。删除不必要的循环。结果:window.location.search window.location.search.substr(1) .split("&") .reduce((acc, param) => { const [key, value] = param.split("=") ; return { ...acc, [key]: value }; }, {})
【解决方案4】:

如果你碰巧使用了 Typescript 并且在 tsconfig.jsonlib 中有 dom,你可以这样做:

const url: URL = new URL(window.location.href);
const params: URLSearchParams = url.searchParams;
// get target key/value from URLSearchParams object
const yourParamValue: string = params.get('yourParamKey');

// To append, you can also leverage api to avoid the `?` check 
params.append('newKey', 'newValue');

【讨论】:

    【解决方案5】:

    这将添加一个全局函数来以映射的形式访问 queryString 变量。

    // -------------------------------------------------------------------------------------
    // Add function for 'window.location.query( [queryString] )' which returns an object
    // of querystring keys and their values. An optional string parameter can be used as
    // an alternative to 'window.location.search'.
    // -------------------------------------------------------------------------------------
    // Add function for 'window.location.query.makeString( object, [addQuestionMark] )'
    // which returns a queryString from an object. An optional boolean parameter can be
    // used to toggle a leading question mark.
    // -------------------------------------------------------------------------------------
    if (!window.location.query) {
        window.location.query = function (source) {
            var map = {};
            source = source || this.search;
    
            if ("" != source) {
                var groups = source, i;
    
                if (groups.indexOf("?") == 0) {
                    groups = groups.substr(1);
                }
    
                groups = groups.split("&");
    
                for (i in groups) {
                    source = groups[i].split("=",
                        // For: xxx=, Prevents: [xxx, ""], Forces: [xxx]
                        (groups[i].slice(-1) !== "=") + 1
                    );
    
                    // Key
                    i = decodeURIComponent(source[0]);
    
                    // Value
                    source = source[1];
                    source = typeof source === "undefined"
                        ? source
                        : decodeURIComponent(source);
    
                    // Save Duplicate Key
                    if (i in map) {
                        if (Object.prototype.toString.call(map[i]) !== "[object Array]") {
                            map[i] = [map[i]];
                        }
    
                        map[i].push(source);
                    }
    
                    // Save New Key
                    else {
                        map[i] = source;
                    }
                }
            }
    
            return map;
        }
    
        window.location.query.makeString = function (source, addQuestionMark) {
            var str = "", i, ii, key;
    
            if (typeof source == "boolean") {
                addQuestionMark = source;
                source = undefined;
            }
    
            if (source == undefined) {
                str = window.location.search;
            }
            else {
                for (i in source) {
                    key = "&" + encodeURIComponent(i);
    
                    if (Object.prototype.toString.call(source[i]) !== "[object Array]") {
                        str += key + addUndefindedValue(source[i]);
                    }
                    else {
                        for (ii = 0; ii < source[i].length; ii++) {
                            str += key + addUndefindedValue(source[i][ii]);
                        }
                    }
                }
            }
    
            return (addQuestionMark === false ? "" : "?") + str.substr(1);
        }
    
        function addUndefindedValue(source) {
            return typeof source === "undefined"
                ? ""
                : "=" + encodeURIComponent(source);
        }
    }
    

    享受吧。

    【讨论】:

      【解决方案6】:

      您可以使用它通过参数名称直接查找值。

      const urlParams = new URLSearchParams(window.location.search);
      const myParam = urlParams.get('myParam');
      

      【讨论】:

        【解决方案7】:

        你可以使用这个函数,从 ?id= 分割字符串

         function myfunction(myvar){
          var urls = myvar;
          var myurls = urls.split("?id=");
          var mylasturls = myurls[1];
          var mynexturls = mylasturls.split("&");
          var url = mynexturls[0];
          alert(url)
        }
        myfunction(window.top.location.href);
        myfunction("http://www.myname.com/index.html?id=dance&emp;cid=in_social_facebook-hhp-food-moonlight-influencer_s7_20160623");
        

        这里是fiddle

        【讨论】:

          【解决方案8】:
            window.location.href.slice(window.location.href.indexOf('?') + 1);
          

          【讨论】:

            【解决方案9】:

            您可以简单地使用URLSearchParams()

            让我们看看我们有一个带有 url 的页面:

            • https://example.com/?product=1&amp;category=game

            在该页面上,您可以使用window.location.search 获取查询字符串,然后使用URLSearchParams() 类提取它们。

            const params = new URLSearchParams(window.location.search)
            
            console.log(params.get('product')
            // 1
            
            console.log(params.get('category')
            // game
            

            另一个使用动态 url(不是来自window.location)的示例,您可以使用 URL 对象提取 url。

            const url = new URL('https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest')
            
            console.log(url.search)
            // ?v=6xJ27BtlM0c&ab_channel=FliteTest
            

            这是一个简单的工作 sn-p:

            const urlInput = document.querySelector('input[type=url]')
            const keyInput = document.querySelector('input[name=key]')
            const button = document.querySelector('button')
            const outputDiv = document.querySelector('#output')
            
            button.addEventListener('click', () => {
                const url = new URL(urlInput.value)
                const params = new URLSearchParams(url.search)
                output.innerHTML = params.get(keyInput.value)
            })
            div {
            margin-bottom: 1rem;
            }
            <div>
              <label>URL</label> <br>
              <input type="url" value="https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest">
            </div>
            
            <div>
              <label>Params key</label> <br>
              <input type="text" name="key" value="v">
            </div>
            
            <div>
              <button>Get Value</button>
            </div>
            
            <div id="output"></div>

            【讨论】:

              【解决方案10】:

              您可以使用window.location 对象的search 属性来获取URL 的查询部分。请注意,它在开头包含问号 (?),以防影响您打算如何解析它。

              【讨论】:

                【解决方案11】:

                您应该查看具有帮助方法的 URL API 以在其中实现此目的,如 URLSearchParams:https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

                目前并非所有现代浏览器都支持此功能,因此请不要忘记对其进行 polyfill(可使用 https://qa.polyfill.io/ 进行 Polyfill)。

                【讨论】:

                  【解决方案12】:
                    var queryObj = {};
                     if(url.split("?").length>0){
                       var queryString = url.split("?")[1];
                     }
                  

                  现在您在 queryString 中有查询部分

                  第一次替换将删除所有空格,第二次将所有“&”部分替换为“,”,最后第三次替换将用“:”代替“=”符号。

                  queryObj = JSON.parse('{"' + queryString.replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
                  

                  假设您有一个类似 abc=123&efg=456 的查询。现在在解析之前,您的查询将被转换为类似 {"abc":"123","efg":"456"} 的内容。现在,当您解析它时,它会在 json 对象中为您提供查询。

                  【讨论】:

                  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
                  【解决方案13】:

                  将其转换为数组,然后用'?'分割

                  var url= 'http://localhost/PMApp/temp.htm?ProjectID=462';
                  
                  url.split('?')[1];     //ProjectID=462
                  

                  【讨论】:

                    【解决方案14】:
                    q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;
                    

                    【讨论】:

                      【解决方案15】:

                      8 年后,单线

                        const search = Object.fromEntries(new URLSearchParams(location.search));
                      

                      不利的一面,它不适用于 IE11

                      解释

                      1. URLSearchParams 接口定义实用方法来处理 URL 的查询字符串。 (来自https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
                      2. Object.fromEntries() 方法将键值对列表转换为对象。 (来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries
                      // For https://caniuse.com/?search=fromEntries
                      > Object.fromEntries(new URLSearchParams(location.search))
                      > {search: "fromEntries"}
                      

                      【讨论】:

                        【解决方案16】:

                        试试这个

                        /**
                         * Get the value of a querystring
                         * @param  {String} field The field to get the value of
                         * @param  {String} url   The URL to get the value from (optional)
                         * @return {String}       The field value
                         */
                        var getQueryString = function ( field, url ) {
                            var href = url ? url : window.location.href;
                            var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
                            var string = reg.exec(href);
                            return string ? string[1] : null;
                        };
                        

                        假设您的网址是http://example.com&this=chicken&that=sandwich。你想得到这个、那个和另一个的值。

                        var thisOne = getQueryString('this'); // returns 'chicken'
                        var thatOne = getQueryString('that'); // returns 'sandwich'
                        var anotherOne = getQueryString('another'); // returns null
                        

                        如果您想使用窗口中的 URL 以外的 URL,您可以将一个作为第二个参数传入。

                        var yetAnotherOne = getQueryString('example', 'http://another-example.com&example=something'); // returns 'something'
                        

                        Reference

                        【讨论】:

                          【解决方案17】:

                          我认为依赖浏览器比任何巧妙的正则表达式更安全:

                          const parseUrl = function(url) { 
                            const a = document.createElement('a')
                            a.href = url
                            return {
                              protocol: a.protocol ? a.protocol : null,
                              hostname: a.hostname ? a.hostname : null,
                              port: a.port ? a.port : null,
                              path: a.pathname ? a.pathname : null,
                              query: a.search ? a.search : null,
                              hash: a.hash ? a.hash : null,
                              host: a.host ? a.host : null  
                            }
                          }
                          
                          console.log( parseUrl(window.location.href) ) //stacksnippet
                          //to obtain a query
                          console.log( parseUrl( 'https://example.com?qwery=this').query )

                          【讨论】:

                            【解决方案18】:

                            这会将查询参数作为关联数组返回

                            var queryParams =[];
                            var query= document.location.search.replace("?",'').split("&");
                            for(var i =0; i< query.length; i++)
                            {
                              if(query[i]){
                                var temp = query[i].split("=");
                                queryParams[temp[0]] = temp[1]
                              }
                            }
                            

                            【讨论】:

                            • 解释或描述应作为您的答案的一部分发布,而不是作为对您的答案的评论。我已将您的评论复制到您的答案中。
                            【解决方案19】:

                            对于 React Native、React 和 For Node 项目,下面的一个正在工作

                            yarn add  query-string
                            
                            import queryString from 'query-string';
                            
                            const parsed = queryString.parseUrl("https://pokeapi.co/api/v2/pokemon?offset=10&limit=10");
                            
                            console.log(parsed.offset) will display 10
                            

                            【讨论】:

                              猜你喜欢
                              • 2018-09-04
                              • 2016-12-31
                              • 2021-07-19
                              • 2014-01-30
                              • 1970-01-01
                              • 1970-01-01
                              • 2013-04-28
                              • 1970-01-01
                              • 2011-07-02
                              相关资源
                              最近更新 更多