logo

The next-generation blog, news, and article for you to start sharing your stories today!

How To Get Query String In Javascript

Sometime we have to  get query string values from url in javascript to perform some operations.

let undersyand it.

A. What is query string ?

So query string is values whicj lyis is http url, Like we have url

http://somexample.com?product_id=1234&category='home'.

Here product_id and category is considered as query string. It may have many values.

 

B. How to get query string in javascript ?

So, to get values from url query string we have a simple Interface in javascript which called URLSearchParams.

Using this interface we can fetch all the keys and values from url query string.

So lets consider a example.

We have this url http://somexample.com?product_id=1234&category='home'or you may have current url of your browser.

let url = `http://somexample.com?product_id='1234'&category='home'`
/* Current url */
let url = window.location.href;
/* Only query string  recommanded pattern */
let url = window.location.search;

/* get the product_id and category */
let params = new URLSearchParams(url);

let category = params.get('category');
let product_id = params.get('product_id');

For more details you can visit https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams .

 

avatar

Vikram Parihar

An editor at Keyscript

Vikram Parihar is an senior software engineer. He is working since 2013 in web development technologies. He works in NodeJS, Angular, Vue, PHP, Laravel, Express JS and various popular technologies.