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?
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With