最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create multiple query keys by URL & URLSearchParams - Stack Overflow

programmeradmin2浏览0评论

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

If I do like this,

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

I achieved

,c&d=e

But I want to have is

;a=c&d=e

How can I get it?

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

If I do like this,

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

I achieved

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

But I want to have is

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

How can I get it?

Share Improve this question asked Dec 9, 2020 at 7:58 kochizufankochizufan 2,4415 gold badges33 silver badges58 bronze badges 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 – prasanth Commented Dec 9, 2020 at 8:11
Add a ment  | 

2 Answers 2

Reset to default 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./hoge');
url.search = p;

console.log(url.href);

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./hoge');
url.search = new URLSearchParams(queryString.stringify(paramJson));
console.log(url.href);
// http://example./hoge?a=b&a=c&d=e
发布评论

评论列表(0)

  1. 暂无评论