---
type: post
id: TePYJZqRJS32Q1rl
title: JavaScript Search Query Snippet
url: >
  https://www.jakubpelak.com/posts/javascript-build-query-snippet
section: posts
tags:
  - Webdev
  - Snippets
  - JavaScript
published_at: 2024-05-30
---

# JavaScript Search Query Snippet

I keep searching for this function seems every other week. I remember the PHP counterpart (link: https://www.php.net/manual/en/function.http-build-query.php text: `http_build_query`), however I am not able to memorize this one.

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

Credit: (link: https://stackoverflow.com/questions/316781/how-to-build-query-string-with-javascript text: Stack Overflow rel: external), (link: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams text: MDN rel: external)

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.*

```javascript
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 : '';
}
```
