Search code examples
javascripturlsearchparams

JS - URLSearchParams - add parameters


I don't seem to be able to add parameters/queries to the URL. I'm trying to add parameters to the url. I'm trying to do it with .set() and .append() but neither seems to do what I thought it'd do. Am I misunderstanding what those methods are meant to do. The desired output should be:

http://newsapi.org/v2/top-headlines?country=gb&q=some_word

Code:

const url = new URL('/v2/top-headlines', 'http://newsapi.org')
const params = new URLSearchParams(url.search);
params.set('country', 'gb');
params.append('q', 'some_word')
console.log(url); // All good http://newsapi.org/v2/top-headlines
console.log(url.search); // empty object
console.log(params); // Empty string


Solution

  • You meant to do this

    const url = new URL('http://newsapi.org/v2/top-headlines');
    
    url.searchParams.set('country', 'gb');
    url.searchParams.set('q', 'some_word');
    console.log(url);
    
    // separately setting the searchParams 
    /*
    const url = new URL('/v2/top-headlines', 'http://newsapi.org'); // (relative,base)
    const params = new URLSearchParams(url.search); // if the url had a queryString already
    params.set('country', 'gb');
    params.set('q', 'some_word');
    url.search = params;
    console.log(url);
    */