简体   繁体   中英

Javascript function to merge / combine two URLSearchParams

I am wondering what is the best most efficient code in Javascript to merge two URLSearchParams, but where one of them has higher priority, let me explain with two examples.

const oldParams = 'foo=one&coo=two'
const newParams = 'roo=three&moo=four'

urlCombine(oldParams, newParams) returns foo=one&coo=two&roo=three&moo=four

So far so good , but let's say we also want to give newParams higher priority so that if the same key exist in both newParams and oldParams the return value should always use the value of newParams , for example.

const oldParams = 'foo=one&coo=two'
const newParams = 'coo=three&foo=four'

urlCombine(oldParams, newParams) returns foo=four&coo=three

Use URLSearchParams to parse the strings into key-value pairs and then combine them.

 const oldParams = 'foo=one&coo=two' const newParams1 = 'roo=three&moo=four' const newParams2 = 'coo=three&foo=four' function urlCombine(a,b,overwrite=false){ a = new URLSearchParams(a); const fn = overwrite? a.set: a.append; for(let [key, value] of new URLSearchParams(b)){ fn.call(a, key, value); } return a.toString(); } console.log(urlCombine(oldParams, newParams1)); console.log(urlCombine(oldParams, newParams2, false)); console.log(urlCombine(oldParams, newParams2, true));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM