J—P

Currently accepting new projects and available for hire.

JavaScript Search Query Snippet

I keep searching for this function seems every other week. I remember the PHP counterpart http_build_query, however I am not able to memorize this one.

new URLSearchParams({
  foo: "Hello",
  bar: "World",
}).toString();

Credit: Stack Overflow, MDN

I only wish there was an option to filter out empty properties, and return string with ? prepended or an empty string when no params were defined.

Update (Jun 13, 2024): Added the function.

function appendSearch(input, filter = true) {
  const entries = filter 
    ? Object.entries(input).filter(([_, val]) => val != null && val !== '') 
    : Object.entries(input);
  const searchParams = new URLSearchParams(entries).toString();
  return searchParams ? '?' + searchParams : '';
}