---
type: collection
section: snippets
generated_at: 2026-04-29T20:47:28+02:00
total_entries: 1
tag_filter: URL
---

# Snippets

## Build a Search Query String in JavaScript

---
type: snippet
id: yreym9gqpwzlxr8o
title: >
  Build a Search Query String in
  JavaScript
url: >
  https://www.jakubpelak.com/snippets/javascript-build-search-query
section: snippets
tags:
  - JavaScript
  - Webdev
  - URL
published_at: 2024-05-30
---

PHP has (link: https://www.php.net/manual/en/function.http-build-query.php text: `http_build_query` target: _blank rel: external noopener) and I never forget it. JavaScript's (link: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams text: `URLSearchParams` target: _blank rel: external noopener) does the same thing but doesn't filter empty values or prepend `?`. This helper wraps it into something you can actually use directly:

```javascript
function buildSearch(params) {
  const query = new URLSearchParams(
    Object.entries(params).filter(([, x]) => x != null && x !== "")
  ).toString()
  return query && "?" + query
}
```

Credit: (link: https://stackoverflow.com/questions/316781/how-to-build-query-string-with-javascript text: Stack Overflow rel: external noopener)

