norbert
norbert

Reputation: 335

How to get multiple named querystring values in jQuery/Javascript?

I've got the following parameters

/Search?category=1&attributes=169&attributes=172&attributes=174&search=all

I'm trying to get just the attributes querystring values as an array in javascript, for example.

attributes = ['169','172','174'] 

Bearing in mind there may be other parameters that are irrelevant such as search or category.

Upvotes: 0

Views: 38

Answers (3)

Kiran Shinde
Kiran Shinde

Reputation: 5992

Might not the proper answer but just tried

var str = "/Search?category=1&attributes=169&attributes=172&attributes=174&search=all";

var str1 = str.split("&");
var attributesArray = [];

  for(var i=0; i<str1.length; i++) {
     if (str1[i].includes("attributes")) {
       attributesArray.push(str1[i].replace("attributes=", ""));
     }
}

Fiddle https://jsfiddle.net/5Lkk0gnz/

Upvotes: 1

Saumya Rastogi
Saumya Rastogi

Reputation: 13709

You can do it like this:

(function() {
  
    function getJsonFromUrl(url) {
	  var query = url.substr(1);
	  var arr = [];
	  query.split("&").forEach(function(part) {
	    var item = part.split("=");
	    arr.push(decodeURIComponent(item[1]));
	  });
	  return arr;
	}

    var url = "https://example.com?category=1&attributes=169&attributes=172&attributes=174&search=all";  
    var params = getJsonFromUrl(url);	
    console.log(params);
  
})();

Hope this helps!

Upvotes: 1

JSelser
JSelser

Reputation: 3630

This should do what you want, assuming you already have your url:

var url = "/Search?ategory=1&attributes=169&attributes=172&attributes=174&search=all";

var attrs = url
  .match(/attributes=\d*/g)
  .map(function(attr){
    return Number(attr.replace("attributes=", ""));
  });

console.log(attrs); //=> [169, 172, 174]

Upvotes: 0

Related Questions