W3docs

How to Get Query String Values in JavaScript

On this page, you can find fast and simple solutions on how to get query string values in JavaScript. Just follow the examples given below to make it work.

While working with JavaScript, it is often necessary to get query string values. In this snippet, we are going to provide you with several efficient solutions in case of getting a specific query string or all query strings.

How to get a specific query string

It is possible to get query string values by using pure JavaScript or jQuery. To implement that, create a function, such as <kbd class="highlighted">getQueryParams</kbd> and add the code given below:

Javascript get query string values

javascript— editable

The function takes <kbd class="highlighted">params</kbd> and <kbd class="highlighted">url</kbd> as parameters. Here you assign the <kbd class="highlighted">url</kbd> to variable <kbd class="highlighted">href</kbd> inside the function.

The <kbd class="highlighted">Regex Pattern</kbd> checks for a value that starts with either <kbd class="highlighted">&</kbd> or ? followed by the parameter passed. It extracts the value after <kbd class="highlighted">=</kbd>, stores it in <kbd class="highlighted">qString</kbd>, and returns it.

How to get all query strings

Getting all query strings differs from getting a single query string. Let’s see how you can solve this problem with the help of below code snippet:

Javascript get all query strings

javascript— editable

Here, an anchor element is created to access the <kbd class="highlighted">search</kbd> property. The <kbd class="highlighted">search</kbd> property returns the complete query string.

After creating an anchor element and assigning the URL to <kbd class="highlighted">href</kbd>, <kbd class="highlighted">search</kbd> returns the query portion of the URL. You can then extract all query parameters by splitting the string using the <kbd class="highlighted">&</kbd> delimiter.

Note: This approach relies on browser APIs and will fail in non-browser environments like Node.js. For modern environments, consider using the built-in URLSearchParams API.