javascriptquery-stringurlsearchparams

Combine the values from all url parameters


Say I have a url that looks like this:

mysite.com/?filter_club_officer=President&filter_club=Houston%20Club

How can I use javascript to get this result?

President-Houston%20Club

I managed to get this far, but I don't know how to get it in the final format:

const searchParams = new URLSearchParams('filter_club_officer=President&filter_club=Houston%20Club');

for (const param of searchParams) {
  param[1];
}


Solution

  • So in the for loop param[1] now refers to the value in each query param key-value pair (i.e., the right side the the equals sign). You now need to store the values in a string, using a "dash" sign as a delimiter.

    const searchParams = new URLSearchParams('filter_club_officer=President&filter_club=Houston%20Club');
    // this will store the final output variable
    let output = '';
    for (const param of searchParams) {
      // add the query param value to output
      output += param[1] + "-";
    }
    // now, output is 'President-Houston Club-'
    // so we wanna remove the final dash:
    
    output = output.slice(0, -1);
    console.log(output);