Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check how many times query param exists in url, if beginning with certain characters

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
    }
}

>Solution :

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading