How to convert an object to a query string in JavaScript

3 Answers

0 votes
const obj = {
  	q: 'JavaScript',
  	lang: 'en',
  	limit: 10
};

const queryString = '?' + new URLSearchParams(obj).toString();

console.log(queryString); 

  
  
  
  
/*
run:
  
"?q=JavaScript&lang=en&limit=10"
  
*/

 



answered Apr 21, 2022 by avibootz
0 votes
const obj = {
  	q: 'JavaScript',
  	lang: 'en',
  	limit: 10
};


const queryString = Object.keys(obj)
    .map(key => `${key}=${obj[key]}`)
    .join('&');

console.log(`https://seek4info.com?${queryString}`);

  
  
  
  
/*
run:
  
"https://seek4info.com?q=JavaScript&lang=en&limit=10"
  
*/

 



answered Apr 21, 2022 by avibootz
edited Apr 21, 2022 by avibootz
0 votes
const obj = {
  	q: 'JavaScript',
  	lang: 'en',
  	limit: 10
};


const queryString = Object.keys(obj)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
    .join('&');
    
    
console.log(`https://seek4info.com?${queryString}`);

  
  
  
  
/*
run:
  
"https://seek4info.com?q=JavaScript&lang=en&limit=10"
  
*/

 



answered Apr 21, 2022 by avibootz
edited Apr 21, 2022 by avibootz

Related questions

1 answer 197 views
3 answers 422 views
1 answer 249 views
1 answer 217 views
3 answers 320 views
3 answers 424 views
...