Get query parameters/URL variables from URL

by admin

Query parameters are used to send pieces of data to a page. Query parameters can contain all kinds of information.

Let’s say you want to display a message to the user when they come from a specific webpage. In order to do that, you pass an additional parameter in the URL and then fetch that parameter with Javascript on the target page. This article shows you the very basics of how to achieve this!

Assuming our URL is:

https://example.com?showMsg=true&msgType=2

We want to retrieve the showMsg and the msgType parameter from this url and show a message to the visitor. The following code snippet retrieves the parameters and uses them to display a message.

//This retrieves the full query string from your URL
const queryString = window.location.search;

//This step fetches the various parameters from the full query string
const urlParms= new URLSearchParams(queryString);

const showMsgValue = urlParams.get('showMsg');
//result = true
const msgTypeValue = urlParams.get('msgType');
//result = 2

//now you can do whatever you want with these values
if(showMsgValue == true) {
alert('MessageType: ' + msgTypeValue);
}

Check if parameter actually exists in query string

If you want to check if the parameter exists in the URL, use the following snippet:

console.log(urlParams.has('showMsg'));
//result = true

console.log(urlParams.has('bananaPhone'));
//result = false

That’s it! Query parameters add a lot of possibilities to create interactive content in your application.

Related Posts

Leave a Comment