4

I want to create url value which have multiple key values in JavaScript.

If I do like this,

    const url = new URL('http://example.com/hoge');
    url.search = new URLSearchParams(['a': ['b', 'c'], 'd': 'e']);
    console.log(url.href);

I achieved

http://example.com/hoge?a=b,c&d=e

But I want to have is

http://example.com/hoge?a=b&a=c&d=e

How can I get it?

1
  • are you sure using same key param used with in url multiple time a=b&a=c . while reading the query value is more annoying Commented Dec 9, 2020 at 8:11

2 Answers 2

6

You can do it this way:

const p = new URLSearchParams();
p.append('a', 'b');
p.append('a', 'c');
p.append('d', 'e');

const url = new URL('http://example.com/hoge');
url.search = p;

console.log(url.href);
Sign up to request clarification or add additional context in comments.

Comments

1

How about using query-string node module

  • [!] This module targets Node.js 6 or later and the latest version of Chrome, Firefox, and Safari. If you want support for older browsers, or, if your project is using create-react-app v1, use version 5: npm install query-string@5.
const queryString = require('query-string');

let paramJson = {
    'a' : ['b', 'c'],
    'd' : 'e'
}

const url = new URL('http://example.com/hoge');
url.search = new URLSearchParams(queryString.stringify(paramJson));
console.log(url.href);
// http://example.com/hoge?a=b&a=c&d=e

Comments

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.