Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URLSearchParams always returning empty

Tags:

javascript

I need to make URLs like example.com?want[]=1,2,3&want[]=1,2,3&want[]=1,2,3

let params = new URLSearchParams();

for(let i in searchArr) {
    params.append('want[]', `${searchArr[i].id},${searchArr[i].quality},${searchArr[i].level}`);
}

console.log(params);

I've verified the given values exists, but it's always showing URLSearchParams {} with no values in console.

Why is it empty?

like image 360
user2722718 Avatar asked Jul 28 '26 21:07

user2722718


2 Answers

URLSearchParams is an object. You need to cast it to a String using toString(), like so:

var params = new URLSearchParams();
params.append('want[]', '1,2,3');
params.append('want[]', '1,2,3');
params.append('want[]', '1,2,3');

console.log(params.toString());

(Note: This will URL-encode characters like "[", "]", and ",")

like image 97
broofa Avatar answered Jul 31 '26 09:07

broofa


You can access values by using any of these methods available on URLSearchParams

  • getAll() -> For a specific search parameter
  • .entries() -> For all key/value pairs
  • .values() -> For all the values

var params = new URLSearchParams();
params.append('want[]', '1,2,3');
params.append('want[]', '1,2,3');
params.append('want[]', '1,2,3');

console.log(params.getAll('want[]'));
console.log([...params.entries()]);
console.log([...params.values()]);
like image 27
Code Maniac Avatar answered Jul 31 '26 11:07

Code Maniac