Get URL Parameters With JavaScript

Using URL parameters is probably the easiest way of passing variables from one webpage to the other. In this article I’m going to present how to get a URL parameter with JavaScript.

get url parameter javascript

The image above presents how will the variables passed in the link. There’s a question mark at the start, then the variable name – value pairs follow, separated by ampersands (&).

The downside of using the GET method is that it’s visible to the visitor and it affects the link of the page. If you don’t prefer this method, you can use the POST method, session Cookies or database to store the variables.

The JavaScript function below parses and returns the parameters.

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

This is how you can pick a value from the variable array.

var number = getUrlVars()["x"];
var mytext = getUrlVars()["text"];

Okay but when the parameter is missing from the URL the value will be undefined. Here’s how to set a default value to the variable:

function getUrlParam(parameter, defaultvalue){
    var urlparameter = defaultvalue;
    if(window.location.href.indexOf(parameter) > -1){
        urlparameter = getUrlVars()[parameter];
        }
	if (urlparameter !== undefined) {
		return urlparameter;
	} else {
		return defaultvalue;
	}
}

Use it like this:

var mytext = getUrlParam('text','Empty');

Encoding and decoding URLs

There are some characters that you can’t pass through the URL. For example try to write a space in a link and press enter. The spaces will be replaced with the %20 code. This is why you have to make sure that you encode and decode the URL parameters every time you use them.

To encode: encodeURI(str)

To decode: decodeURI(str)

The functions take a string as an input.