Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the size (or length) for URL searchParams?

Tags:

javascript

How get size from URLSearchParams? I found

Array.from(url.searchParams).length

this answer in here https://github.com/whatwg/url/issues/163

It most correct answer?

like image 918
zloctb Avatar asked Feb 10 '17 09:02

zloctb


2 Answers

TL;DR: It depends on whether or not you care about unique keys.

The normal case, in which the searchParams is a map (unique keys), works fine:

const url = new URL("protocol://domain?query=value1&query1=value2&query2=value");
console.log(Array.from(url.searchParams).length);
// Output is 3

Yet you need to be careful when searchParams isn't a map:

const url = new URL("protocol://domain?query=value1&query=value2&query2=value");
console.log(Array.from(url.searchParams).length);
// Output is still 3

In this case, when converting to an array, the array is [["query", "value1"], ["query", "value2"], ["query2", "value"]]. This could be quite confusing if you expect searchParams to be a map.

In this case, in order to find the unique keys, you should extract them using something similar to this:

const url = new URL("protocol://domain?query=value1&query=value2&query2=value");
const searchParams = Array.from(url.searchParams);
const searchParamsUniqueKeys = [];

for (const p of searchParams) {
  if (!searchParamsUniqueKeys.includes(p[0])) {
    searchParamsUniqueKeys.push(p[0]);
  }
}
console.log(searchParamsUniqueKeys.length);
// Output is 2
like image 173
Lior Pollak Avatar answered Nov 14 '22 01:11

Lior Pollak


Yes, you can attain the length of the searchParams property using Array.from(url.searchParams).length:

Example:

const url = new URL("protocol://domain?query=value1&query=value2&query2=value");
const size = Array.from(url.searchParams).length

console.log(size)

You can also use the ES6 array spread syntax:

const url = new URL("protocol://domain?query=value1&query=value2&query2=value");
const size = [...url.searchParams].length

console.log(size)
like image 23
hitautodestruct Avatar answered Nov 14 '22 02:11

hitautodestruct