Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of parameters in query string

How can I count the number of parameters query strings passed? e.g.

www.abc.com/product.html?product=furniture&&images=true&&stocks=yes

I want to be able to get the answer as 3 1. product=furniture 2. images=true 3. stocks=yes

var url = window.location.href;
var arr = url.split('=');
console.log(url.length)
like image 903
Bekki Avatar asked Mar 15 '23 01:03

Bekki


2 Answers

You can use String's match:

var matches = str.match(/[a-z\d]+=[a-z\d]+/gi);
var count = matches? matches.length : 0;
like image 144
hindmost Avatar answered Mar 25 '23 07:03

hindmost


first get the location of a question mark character ? in the required url

var pos = location.href.indexOf("?");
if(pos==-1) return [];
query = location.href.substr(pos+1);

then get the array of parameters:

var result = {};
query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
});

Then count the length of result as

result.length;
like image 20
Funkky Exalter Avatar answered Mar 25 '23 07:03

Funkky Exalter