How to get multiple parameters with the same name from a URL in JavaScript

The question asked endlessly is how to get a variable from a URL. In all my searches, I found some very good ways to get A=aValuefrom url.

But my question is: I need

?Company=FLHS&Device=Crosstown_PCC_01&A=aValue&A=secondAValue

I need an array of two A in the url, and I need to know what aValuewas first and secondAValuewas second

I have jquery Mobile.

Update

So this is what I have now

var urlParamDevice = getURLParameter('DeviceID');


function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]
    );

getURLParameter (name) should be a little more reliable.

Update 2, 2014/03/07 Here is what I came up with from the proposed answer.

function getQueryParams(name) {
   qs = location.search;

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

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

   return params;
}
+4
source share
3 answers

function getparamNameMultiValues(paramName){
	    var sURL = window.document.URL.toString();
	    var value =[];
	    if (sURL.indexOf("?") > 0){
	        var arrParams = sURL.split("?");
	        var arrURLParams = arrParams[1].split("&");
	        for (var i = 0; i<arrURLParams.length; i++){
	            var sParam =  arrURLParams[i].split("=");
	            console.log(sParam);
	            if(sParam){
		            if(sParam[0] == paramName){
		            	if(sParam.length>0){
		            		value.push(sParam[1].trim());
		            	}
		            }
	            }
	        }
	    }
	    return value.toString();
	}
Run code
+1

: fooobar.com/questions/5739/... -

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

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

    while (tokens = re.exec(qs)) {
        params.push({k:decodeURIComponent(tokens[1]),v:decodeURIComponent(tokens[2])});
    }

    return params;
}

var obj = 
  getQueryParams("?Company=FLHS&Device=Crosstown_PCC_01&A=aValue&A=secondAValue")

obj[0] is {k: "Company", v: "FLHS"}
obj[1] is {k: "Device", v: "Crosstown_PCC_01"}
obj[2] is {k: "A", v: "aValue"}
obj[3] is {k: "A", v: "secondAValue"}
0

Sometimes this will work:

A[]=aValue&A[]=secondAValue

Otherwise, you can do this:

A_1=aValue&A_2secondAValue

You can underline or use basically any character of your choice to distinguish between the values ​​of querystring "A"

0
source

Source: https://habr.com/ru/post/1530308/


All Articles