Using this: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
If I have a few color[]
queries in the url and want to remove just red
, is this the best algorithm to use?
In the following example, I used .delete()
method and then re-added the ones removed. Is there a more efficient way?
function log(h){document.getElementById('log').innerHTML += h+'<br>';} let uri = 'http://localhost/?color[]=red&color[]=blue&color[]=green&page=2'; log(uri); log(''); //space -------- let U = new URL(uri); let search_params = U.searchParams; log('current search params:'); for(let [k,v] of search_params.entries()){ log(`${k}: ${v}`); } log(''); //space -------- let colors = search_params.getAll('color[]'); log('colors: '+JSON.stringify(colors,null,2)); log(''); //space -------- //remove red by removing all and adding the rest search_params.delete('color[]'); log('params after delete all colors: '); for(let [k,v] of search_params.entries()){ log(`${k}: ${v}`); } log(''); //space -------- for(let v of colors){ if(v !== 'red'){ search_params.append('color[]',v); } } log('colors after adding all but red: '+JSON.stringify(search_params.getAll('color[]'),null,2)); log(''); //space -------- log('params after removing red: '); for(let [k,v] of search_params.entries()){ log(`${k}: ${v}`); }
#log { min-height:600px; min-width:600px;}
<div id="log"></div>
You can use the filter function
let search_params_without_red = new URLSearchParams(Array.from(search_params).filter(color => color[1] !== `red`))
with some help from here: https://github.com/whatwg/url/issues/335
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.