如何使用JavaScript从当前URL获取查询字符串?

时间:2012-03-26 10:30:43

标签: javascript query-string

我有这样的网址:

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

我需要做的是在?符号(查询字符串)之后获取详细信息 - 即ProjectID=462。我怎样才能使用JavaScript?

到目前为止我所做的是:

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

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

18 个答案:

答案 0 :(得分:180)

查看关于window.location的{​​{3}}。

QueryString在window.location.search

中可用

适用于旧版浏览器的解决方案

MDN提供了一个示例(在上面引用的文章中不再提供)如何获取QueryString中可用的单个键的get值。像这样:

function getQueryStringValue (key) {  
  return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));  
}  

// Would write the value of the QueryString-variable called name to the console  
console.log(getQueryStringValue("name")); 

在现代浏览器中

在现代浏览器中,您具有URL接口的MDN article属性,该属性返回searchParams个对象。返回的对象有许多方便的方法,包括get-method。所以上面例子的等价物是:

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

答案 1 :(得分:49)

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

示例:

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

答案 2 :(得分:8)

decodeURI(window.location.search)
  .replace('?', '')
  .split('&')
  .map(param => param.split('='))
  .reduce((values, [ key, value ]) => {
    values[ key ] = value
    return values
  }, {})

答案 3 :(得分:7)

这将添加一个全局函数来访问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);
    }
}

享受。

答案 4 :(得分:4)

您可以使用此功能,对于来自?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

答案 5 :(得分:3)

  window.location.href.slice(window.location.href.indexOf('?') + 1);

答案 6 :(得分:2)

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

答案 7 :(得分:2)

  var queryObj = {};
   if(url.split("?").length>0){
     var queryString = url.split("?")[1];
   }

现在你在queryString

中有了查询部分

首先替换将删除所有空格,第二个将替换所有&#39;&amp;&#39;部分与&#34;,&#34;最后,第三个替换将放置&#34;:&#34;代替&#39; =&#39;迹象。

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

因此,假设您有一个类似 abc = 123&amp; efg = 456 的查询。现在,在解析之前,您的查询将被转换为{&#34; abc&#34;:&#34; 123&#34;,&#34; efg&#34;:&#34; 456&#34;}。现在,当你解析它时,它将在json对象中提供你的查询。

答案 8 :(得分:1)

将其转换为数组然后用&#39;?&#39;

拆分
var url= 'http://localhost/PMApp/temp.htm?ProjectID=462';

url.split('?')[1];     //ProjectID=462

答案 9 :(得分:1)

您应该查看具有帮助程序方法的URL API,以URLSearchParamshttps://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

为其实现此目的

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

答案 10 :(得分:1)

如果您碰巧使用了 Typescript ,并且在tsconfig.json lib 中具有 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');

答案 11 :(得分:1)

q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;

答案 12 :(得分:0)

尝试这个

/**
 * 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,则可以将URL作为第二个参数传递。

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

Reference

答案 13 :(得分:0)

您可以将其用于通过参数名称直接查找值。

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

答案 14 :(得分:0)

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

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 )

答案 15 :(得分:0)

这将以关联数组的形式返回查询参数

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]
  }
}

答案 16 :(得分:0)

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"}

答案 17 :(得分:0)

对于 React Native、React 和对于 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