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 : '';
}
- Blank Bookmarks Slate Sep 24, 2024
- JavaScript Search Query Snippet May 30, 2024
- Vercel Open Graph Card With No Framework Mar 13, 2024
- Svelte Grid Snippet Mar 02, 2024
- Hello World Mar 01, 2024