How to extract query string from url parameter using JavaScript


Query string are helpful when need to pass values to a page. It start with ? and multiple statement can be added using &

We can also use window.location.href to grab the current page URL in JavaScript

Here is an example query string

example.com/?pid=1001&type=electronics

Using JavaScript we can access the query string easily with window.location.search. Let’s have have query search example

const queryString = window.location.search;
 console.log(queryString);
 // ?pid=1001&type=electroni        

Find a Parameter

To find/sear a URL Parameter say PID , we need to use URLSearchParams and using the output we can access the param value too as follows

const urlParams = new URLSearchParams(queryString);
 const pid = urlParams.get('pid')
 console.log(pid); 

Following JavaScript post may help you

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.