5

How to properly use UrlSearchParams to create url a structure like the following:

example.org?tag[]=one&tag[]=two&tag[]=other

When I use Url Params as presented below:

let params = new URLSearchParams();
params.append('tag', 'one');
params.append('tag', 'two');
params.append('tag', 'other');

The Url looks like this:

example.org?tag=one&tag=two&tag=other

This approach causes some problems on web servers because they treat that query string the same way as ?tag=one. The server gets only the first value if there are no brackets present.

0

2 Answers 2

9

I think you are looking for this:

let params = new URLSearchParams();
params.append('tag[]', 'one');
params.append('tag[]', 'two');
params.append('tag[]', 'other');
Sign up to request clarification or add additional context in comments.

1 Comment

This does no longer work, since the [] are encoded now.
2

I guess you can do something like this, but I haven't tested it:

let params = new URLSearchParams();
params.append('tag[0]', 'one');
params.append('tag[1]', 'two');
params.append('tag[2]', 'other');

1 Comment

Hi how can we pass key in tag dynamically. I mean as a variable. eg: 'tag[key]'. I want to use it a for loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.