How to Get Query String Parameters from URL using JavaScript

Query string in URL is very useful to work with dynamic content. Generally, server-side language is used to get query string from URL. But you can also get query string parameters from URL to client-side. The query string parameters and values can be easily retrieved from the URL using JavaScript.

The location search property in JavaScript returns the query string part of a URL. The example code shows you how to get query string from URL using JavaScript.

Assume that the URL is http://codexworld.com/index.php?type=product&id=1234

Get Query String Parameters
Use location.search to get query string parameters including the question mark (?).

var queryString = location.search;
// ?type=product&id=1234

Get Query String Parameter Value
The URLSearchParams object is the easiest way to get query string parameter value with JavaScript. The following code shows how to use URLSearchParams to work with the query string of a URL.

var urlParams = new URLSearchParams(location.search);

urlParams.has('type');  // true
urlParams.get('id');    // 1234
urlParams.getAll('id'); // ["1234"]
urlParams.toString();   // type=product&id=1234

3 Comments

  1. Thamizharasan.P Said...
  2. Al Said...

Leave a reply

keyboard_double_arrow_up