如何从GET参数中获取值?

我有一个带有一些GET参数的URL,如下所示:

www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5

我需要获得 c 的全部 Value . 我试图读取URL,但我只得到 m2 . 如何使用JavaScript执行此操作?

回答(30)

2 years ago

这是我的解决方案 . 正如Andy E在回答this question时所建议的那样,如果's repeatedly building various regex strings, running loops etc just to get a single value. So, I'已经提出了一个更简单的脚本来返回单个对象中的所有GET参数,那么它的表现就是's not good for your script' . 您应该只调用一次,将结果分配给变量,然后在将来的任何时候,使用适当的密钥从该变量中获取所需的任何值 . 请注意,它还会处理URI解码(例如%20)并替换为空格:

function getUrlQueryParams(url) {
  var queryString = url.split("?")[1];
  var keyValuePairs = queryString.split("&");
  var keyValue = [];
  var queryParams = {};
  keyValuePairs.forEach(function(pair) {
    keyValue = pair.split("=");
    queryParams[keyValue[0]] = decodeURIComponent(keyValue[1]).replace(/\+/g, " ");
});
  return queryParams;
}

所以,这里有一些脚本测试供您查看:

// Query parameters with strings only, no special characters.
var currentParams = getUrlQueryParams("example.com/foo?number=zero");
alert(currentParams["number"]); // Gives "zero".

// For the URL you stated above...
var someParams = getUrlQueryParams("www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ");
alert(someParams["c"]); // Gives "m2-m3-m4-m5".

// For a query params with URI encoding...
var someParams = getUrlQueryParams("www.example.com/t.html?phrase=a%20long%20shot&location=Silicon+Valley%2C+USA");
alert(someParams["phrase"]); // Gives "a long shot".
alert(someParams["location"]); // Gives "Silicon Valley, USA".

2 years ago

我需要读取URL GET变量并根据url参数完成操作 . 我搜索了一个解决方案的高低,并遇到了这一小段代码 . 它基本上读取当前页面URL,在URL上执行一些正则表达式,然后将url参数保存在关联数组中,我们可以轻松访问 .

举个例子,如果我们在底部的javascript中有以下url .

http://TestServer/Pages/NewsArchive.aspx?year=2013&Month=July

我们需要做的就是获取参数id和page来调用它:

The Code will be:

<script type="text/javascript">
var first = getUrlVars()["year"];
var second = getUrlVars()["Month"];

alert(first);
alert(second);
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>

2 years ago

这个问题的答案太多了,所以我又补充了一个 .

/**
 * parses and returns URI query parameters 
 * 
 * @param {string} param parm
 * @param {bool?} asArray if true, returns an array instead of a scalar 
 * @returns {Object|Array} 
 */
function getURIParameter(param, asArray) {
    return document.location.search.substring(1).split('&').reduce(function(p,c) {
        var parts = c.split('=', 2).map(function(param) { return decodeURIComponent(param); });
        if(parts.length == 0 || parts[0] != param) return (p instanceof Array) && !asArray ? null : p;
        return asArray ? p.concat(parts.concat(true)[1]) : parts.concat(true)[1];
    }, []);
}

用法:

getURIParameter("id")  // returns the last id or null if not present
getURIParameter("id", true) // returns an array of all ids

这可以处理空参数(那些没有 "=value" 的密钥),标量和基于数组的值检索API的暴露,以及正确的URI组件解码 .

2 years ago

您可以在 location.search 中获取查询字符串,然后您可以在问号后分割所有内容:

var params = {};

if (location.search) {
    var parts = location.search.substring(1).split('&');

    for (var i = 0; i < parts.length; i++) {
        var nv = parts[i].split('=');
        if (!nv[0]) continue;
        params[nv[0]] = nv[1] || true;
    }
}

// Now you can get the parameters you want like so:
var abc = params.abc;

2 years ago

这是我做的:

var uriParams = getSearchParameters();
alert(uriParams.c);


// background functions:

// Get object/associative array of URL parameters
function getSearchParameters () {
  var prmstr = window.location.search.substr(1);
  return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}

// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
  var params = {},
      prmarr = prmstr.split("&");

  for (var i = 0; i < prmarr.length; i++) {
    var tmparr = prmarr[i].split("=");
    params[tmparr[0]] = tmparr[1];
  }
  return params;
}

2 years ago

// http:localhost:8080/path?param_1=a&param_2=b
var getParamsMap = function () {
    var params = window.location.search.split("&");
    var paramsMap = {};
    params.forEach(function (p) {
        var v = p.split("=");
        paramsMap[v[0]]=decodeURIComponent(v[1]);
    });
    return paramsMap;
};

// -----------------------

console.log(getParamsMap()["param_1"]);  // should log "a"

2 years ago

我用

function getVal(str) {
    var v = window.location.search.match(new RegExp('(?:[\?\&]'+str+'=)([^&]+)'));
    return v ? v[1] : null;
}

2 years ago

JavaScript本身没有内置处理查询字符串参数的内容 .

在(现代)浏览器中,您可以使用URL object;

var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);

对于较旧的浏览器(包括Internet Explorer),您可以使用this polyfill或此答案的原始版本中的代码,该代码早于 URL

您可以访问 location.search ,这将使您从 ? 字符到URL的末尾或片段标识符的开头(#foo),以先到者为准 .

然后你可以解析它:

function parse_query_string(query) {
  var vars = query.split("&");
  var query_string = {};
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    var key = decodeURIComponent(pair[0]);
    var value = decodeURIComponent(pair[1]);
    // If first entry with this name
    if (typeof query_string[key] === "undefined") {
      query_string[key] = decodeURIComponent(value);
      // If second entry with this name
    } else if (typeof query_string[key] === "string") {
      var arr = [query_string[key], decodeURIComponent(value)];
      query_string[key] = arr;
      // If third or later entry with this name
    } else {
      query_string[key].push(decodeURIComponent(value));
    }
  }
  return query_string;
}

var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);

您可以从当前页面的URL获取查询字符串:

var query = window.location.search.substring(1);
var qs = parse_query_string(query);

2 years ago

See this

function getURLParameters(paramName)
{
    var sURL = window.document.URL.toString();
    if (sURL.indexOf("?") > 0)
    {
        var arrParams = sURL.split("?");
        var arrURLParams = arrParams[1].split("&");
        var arrParamNames = new Array(arrURLParams.length);
        var arrParamValues = new Array(arrURLParams.length);

        var i = 0;
        for (i = 0; i<arrURLParams.length; i++)
        {
            var sParam =  arrURLParams[i].split("=");
            arrParamNames[i] = sParam[0];
            if (sParam[1] != "")
                arrParamValues[i] = unescape(sParam[1]);
            else
                arrParamValues[i] = "No Value";
        }

        for (i=0; i<arrURLParams.length; i++)
        {
            if (arrParamNames[i] == paramName)
            {
                //alert("Parameter:" + arrParamValues[i]);
                return arrParamValues[i];
            }
        }
        return "No Parameters Found";
    }
}

2 years ago

以下是用于将url查询参数解析为Object的angularJs源代码:

function tryDecodeURIComponent(value) {
  try {
    return decodeURIComponent(value);
  } catch (e) {
    // Ignore any invalid uri component
  }
}

function isDefined(value) {return typeof value !== 'undefined';}

function parseKeyValue(keyValue) {
  keyValue = keyValue.replace(/^\?/, '');
  var obj = {}, key_value, key;
  var iter = (keyValue || "").split('&');
  for (var i=0; i<iter.length; i++) {
    var kValue = iter[i];
    if (kValue) {
      key_value = kValue.replace(/\+/g,'%20').split('=');
      key = tryDecodeURIComponent(key_value[0]);
      if (isDefined(key)) {
        var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
        if (!hasOwnProperty.call(obj, key)) {
          obj[key] = val;
        } else if (isArray(obj[key])) {
          obj[key].push(val);
        } else {
          obj[key] = [obj[key],val];
        }
      }
    }
  };
  return obj;
}

alert(JSON.stringify(parseKeyValue('?a=1&b=3&c=m2-m3-m4-m5')));

您可以将此功能添加到 window.location

window.location.query = function query(arg){
  q = parseKeyValue(this.search);
  if (!isDefined(arg)) {
    return q;
  }      
  if (q.hasOwnProperty(arg)) {
    return q[arg];
  } else {
    return "";
  }
}

// assuming you have this url :
// http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5

console.log(window.location.query())

// Object {a: "1", b: "3", c: "m2-m3-m4-m5"}

console.log(window.location.query('c'))

// "m2-m3-m4-m5"

2 years ago

我在这里发布一个例子 . 但它是在jQuery中 . 希望它会帮助别人:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>

<!-- URL:  www.example.com/correct/?message=done&year=1990-->

<script type="text/javascript">
$(function(){
    $.url.attr('protocol')  // --> Protocol: "http"
    $.url.attr('path')          // --> host: "www.example.com"
    $.url.attr('query')         // --> path: "/correct/"
    $.url.attr('message')   // --> query: "done"
    $.url.attr('year')      // --> query: "1990"
});
</script>

2 years ago

我写了一个更简单优雅的解决方案 .

var arr = document.URL.match(/room=([0-9]+)/)
var room = arr[1];

2 years ago

我做了一个功能:

var getUrlParams = function (url) {
  var params = {};
  (url + '?').split('?')[1].split('&').forEach(function (pair) {
    pair = (pair + '=').split('=').map(decodeURIComponent);
    if (pair[0].length) {
      params[pair[0]] = pair[1];
    }
  });
  return params;
};

更新5/26/2017,这是一个ES7实现(运行babel预设阶段0,1,2或3):

const getUrlParams = url => `${url}?`.split('?')[1]
  .split('&').reduce((params, pair) =>
    ((key, val) => key ? {...params, [key]: val} : params)
    (...`${pair}=`.split('=').map(decodeURIComponent)), {});

一些测试:

console.log(getUrlParams('https://google.com/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('https://google.com/')); // Will log {}
console.log(getUrlParams('a=1&b=2&c')); // Will log {}

更新3/26/2018,这是一个Typescript实现:

const getUrlParams = (search: string) => `${search}?`
  .split('?')[1]
  .split('&')
  .reduce(
    (params: object, pair: string) => {
      const [key, value] = `${pair}=`
        .split('=')
        .map(decodeURIComponent)

      return key.length > 0 ? { ...params, [key]: value } : params
    },
    {}
  )

2 years ago

使用URLSearchParams的超级简单方法 .

function getParam(param){
  return new URLSearchParams(window.location.search).get(param);
}

它目前支持Chrome,Firefox,Safari,Edge和others .

2 years ago

浏览器供应商已经通过URL和URLSearchParams实现了本机方式 .

let url = new URL('http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5');
let searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('c'));  // outputs "m2-m3-m4-m5"

目前支持Firefox,Opera,Safari,Chrome和Edge . 有关浏览器支持列表see here .

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams https://developer.mozilla.org/en-US/docs/Web/API/URL/URL

https://url.spec.whatwg.org/

Google的工程师Eric Bidelman,recommends使用此polyfill来支持不受支持的浏览器 .

2 years ago

还有一个建议 .

已经有一些好的答案,但我发现它们不必要地复杂且难以理解 . 这很简单,并返回一个简单的关联数组,其键名与URL中的标记名相对应 .

我为想要学习的人添加了一个带有评论的版本 .

请注意,这依赖于jQuery($ .each)的循环,我建议使用它而不是forEach . 我发现使用jQuery确保跨浏览器兼容性更简单,而不是插入单独的修补程序来支持旧浏览器中不支持的新功能 .

编辑:在我写完这篇文章之后,我注意到埃里克·艾略特的答案,几乎是相同的,尽管它使用forEach,而我一般反对(出于上述原因) .

function getTokens(){
    var tokens = [];
    var query = location.search;
    query = query.slice(1);
    query = query.split('&');
    $.each(query, function(i,value){    
        var token = value.split('=');   
        var key = decodeURIComponent(token[0]);     
        var data = decodeURIComponent(token[1]);
        tokens[key] = data;
    });
    return tokens;
}

评论版:

function getTokens(){
    var tokens = [];            // new array to hold result
    var query = location.search; // everything from the '?' onward 
    query = query.slice(1);     // remove the first character, which will be the '?' 
    query = query.split('&');   // split via each '&', leaving us an array of something=something strings

    // iterate through each something=something string
    $.each(query, function(i,value){    

        // split the something=something string via '=', creating an array containing the token name and data
        var token = value.split('=');   

        // assign the first array element (the token name) to the 'key' variable
        var key = decodeURIComponent(token[0]);     

        // assign the second array element (the token data) to the 'data' variable
        var data = decodeURIComponent(token[1]);

        tokens[key] = data;     // add an associative key/data pair to our result array, with key names being the URI token names
    });

    return tokens;  // return the array
}

对于下面的示例,我们将假设此地址:

http://www.example.com/page.htm?id=4&name=murray

您可以将URL标记分配给您自己的变量:

var tokens = getTokens();

然后按名称引用每个URL令牌,如下所示:

document.write( tokens['id'] );

这将打印“4” .

您也可以直接从函数中引用令牌名称:

document.write( getTokens()['name'] );

...会打印出“默里” .

2 years ago

我很久以前就发现了这个问题:

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,    
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }

然后这样称呼它:

var fType = getUrlVars()["type"];

2 years ago

对于 Single Parameter Value 这样的index.html?msg = 1使用以下代码,

$(window).load(function(){
    queryString();
});

function queryString()
{
    var queryString = window.location.search.substring(1);
    var varArray = queryString.split("="); //eg. index.html?msg=1

    var param1 = varArray[0];
    var param2 = varArray[1];

}

对于 All Parameter 使用以下代码,

$(window).load(function(){
    queryString();
});

function queryString()
{
    var queryString = window.location.search;
    var varArray = queryString.split("&");
    for (var i=0;i<varArray.length;i++) {
      var param = varArray[i].split("=");
        //parameter-value pair
    }
}

2 years ago

我们可以在不循环所有参数的情况下以更简单的方式获取 c 参数值,请参阅下面的jQuery以获取参数 .

1. To Get the Parameter value:

var url = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5";

url.match(**/(c=)[0-9A-Za-z-]+/ig**)[0].replace('c=',"")

(要么)

url.match(**/(c=)[0-z-]+/ig**)[0].replace('c=',"")

作为回报串

“m2-m3-m4-m5”

2. To Replace the parameter value:

var url = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5";

url.replace(**/(c=)[0-9A-Za-z-]+/ig, "c=m2345"**)

2 years ago

或者,如果您不想重新发明URI解析轮,请使用URI.js

要获取名为foo的参数的值:

new URI((''+document.location)).search(true).foo

这是做什么的

  • 将document.location转换为字符串(它是一个对象)

  • 将该字符串提供给URI.js的URI类construtor

  • 调用search()函数以获取url的搜索(查询)部分
    (传递true告诉它输出一个对象)

  • 访问结果对象上的foo属性以获取值

这是一个小提琴.... http://jsfiddle.net/m6tett01/12/

2 years ago

简单的方法

function getParams(url){
        var regex = /[?&]([^=#]+)=([^&#]*)/g,
            params = {},
            match;
        while(match = regex.exec(url)) {
            params[match[1]] = match[2];
        }
        return params;
    }

然后像getParams(url)一样调用它

2 years ago

function getParamValue(param) {
    var urlParamString = location.search.split(param + "=");
    if (urlParamString.length <= 1) return "";
    else {
        var tmp = urlParamString[1].split("&");
        return tmp[0];
    }
}

无论参数是否为最后,这都适用于您的情况 .

2 years ago

window.location.href.split("?")

然后忽略第一个指数

Array.prototype.slice.call(window.location.href.split("?"), 1)

返回url参数的数组

var paramArray = Array.prototype.slice.call(window.location.href.split(/[?=]+/), 1);
var paramObject = paramArray.reduce(function(x, y, i, a){ (i%2==0) ?  (x[y] = a[i+1]) : void 0; return x; }, {});

paramObject包含所有映射为js对象的参数,有点冗长/ hacky但也有功能

2 years ago

This is an easy way to check just one parameter:

示例网址:

http://myserver/action?myParam=2

示例Javascript:

var myParam = location.search.split('myParam=')[1]

如果URL中存在“myParam”...变量myParam将包含“2”,否则它将是未定义的 .

在这种情况下,也许你想要一个默认值:

var myParam = location.search.split('myParam=')[1] ? location.search.split('myParam=')[1] : 'myDefaultValue';

Update: 这效果更好:

var url = "http://www.example.com/index.php?myParam=384&login=admin"; // or window.location.href for current url
    var captured = /myParam=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
    var result = captured ? captured : 'myDefaultValue';

即使URL充满参数,它也能正常工作 .

2 years ago

这是一个递归解决方案,没有正则表达式,并且具有最小的突变(只有params对象被突变,我认为这在JS中是不可避免的) .

It's awesome because it:

  • 是递归的

  • 处理同名的多个参数

  • 处理格式错误的参数字符串(缺少值,等等)

  • 不是't break if ' ='在值中

  • 执行URL解码

  • 最后,它很棒,因为它......唉!

Code:

var get_params = function(search_string) {

  var parse = function(params, pairs) {
    var pair = pairs[0];
    var parts = pair.split('=');
    var key = decodeURIComponent(parts[0]);
    var value = decodeURIComponent(parts.slice(1).join('='));

    // Handle multiple parameters of the same name
    if (typeof params[key] === "undefined") {
      params[key] = value;
    } else {
      params[key] = [].concat(params[key], value);
    }

    return pairs.length == 1 ? params : parse(params, pairs.slice(1))
  }

  // Get rid of leading ?
  return search_string.length == 0 ? {} : parse({}, search_string.substr(1).split('&'));
}

var params = get_params(location.search);

// Finally, to get the param you want
params['c'];

2 years ago

我见过的大多数实现都错过了URL解码名称和值 .

这是一个通用的实用函数,也可以进行正确的URL解码:

function getQueryParams(qs) {
    qs = qs.split('+').join(' ');

    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }

    return params;
}

//var query = getQueryParams(document.location.search);
//alert(query.foo);

2 years ago

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

// Usage for URL: http://my.site.com/location?locationId=53cc272c0364aefcb78756cd&shared=false
var id = getUrlVars()["locationId"];

来自这里:http://jquery-howto.blogspot.ru/2009/09/get-url-parameters-values-with-jquery.html

2 years ago

source

function gup( name, url ) {
    if (!url) url = location.href;
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( url );
    return results == null ? null : results[1];
}
gup('q', 'hxxp://example.com/?q=abc')

2 years ago

ECMAScript 6解决方案:

var params = window.location.search
  .substring(1)
  .split("&")
  .map(v => v.split("="))
  .reduce((map, [key, value]) => map.set(key, decodeURIComponent(value)), new Map())

2 years ago

我使用parseUri库 . 它可以让你完全按照你的要求去做:

var uri = 'www.test.com/t.html&a=1&b=3&c=m2-m3-m4-m5';
var c = uri.queryKey['c'];
// c = 'm2-m3-m4-m5'