0

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.

3 Answers 3

1

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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!

1 Comment

Seriously? jQuery?
0

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]

2 Comments

It’s probably not a good idea to assume the value of the attributes key will be all digits. Better to match any char up to (&|$), non-greedy. Then, since it’ll be uri encoded, decode it.
True that, also this minimal code should be enhanced and adapted to OP particular problem, say, by making a function or something

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.