I wanted to check how many times, a query param exists in a URL, which begins with org
.
For example: www.myurl.com/booking?org[0]=LGW&org[1]=LTN&org[2]=SEN&org[3]=STN
Sometimes the URL might contain org
once. Sometimes it maybe 10 times. Basically, How can I loop through the url. But it will always be org[number]=value
Here's a solution I have tried which works. Is there a better way to do this?
let url1 = new URL(window.location.href);
let searchParams = Array.from(url1.searchParams);
let searchParamsUniqueKeys = [];
for (const p of searchParams) {
if (p[0].substring(0, 3) == "org") {
console.log("p", p[0])
}
}
This console.logs:
p org[0]
p org[1]
p org[2]
p org[3]
But adding .length
as below, console.logs 6
. Not sure why...
let url1 = new URL(window.location.href);
let searchParams = Array.from(url1.searchParams);
let searchParamsUniqueKeys = [];
for (const p of searchParams) {
if (p[0].substring(0, 3) == "org") {
console.log("p", p[0].length)
}
}
CodePudding user response:
You can use a code like that:
let url = new URL('https://www.myurl.com/?booking&org[0]=LGW&org[1]=LTN&org[2]=SEN&org[3]=STN');
console.log([...url.searchParams].map(el => el.includes('org')).length);
Reference:
CodePudding user response:
I found a solution, based on what I posted above. Pushing the values into an array and then calculating the length.
let url1 = new URL(window.location.href);
let searchParams = Array.from(url1.searchParams);
let searchParamsUniqueKeys = [];
for (const p of searchParams) {
if (p[0].substring(0, 3) == "org") {
console.log("p", p[0])
searchParamsUniqueKeys.push(p[0])
}
}
console.log("result", searchParamsUniqueKeys.length);