Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URLSearchParams returning null for the first query string

Why is timeperiod null

const url = 'http://example.com?timeperiod=lasttwentyeightdays&pagesize=20'
const args =  new URLSearchParams(url);
alert('timeperiod='+args.get('timeperiod') + ' and pagesize='+ args.get('pagesize'));

But in the below code it works

  const url = 'http://example.com?x=c&timeperiod=lasttwentyeightdays&pagesize=20'
  const args =  new URLSearchParams(url);
  alert('timeperiod='+args.get('timeperiod') + ' and pagesize='+ args.get('pagesize'));
like image 919
aWebDeveloper Avatar asked Mar 11 '19 14:03

aWebDeveloper


Video Answer


1 Answers

You need to create a URL object and then retrieve the params with url.search:

See

const url = new URL('http://example.com?timeperiod=lasttwentyeightdays&pagesize=20');

const args =  new URLSearchParams(url.search);

console.log(`timeperiod=${args.get('timeperiod')} and pagesize=${ args.get('pagesize')}`);
like image 108
aristarinsv Avatar answered Oct 18 '22 23:10

aristarinsv