Getting and Setting URL Parameters with JavaScript

Although there’s probably plenty of good plugins to do this my code for getting and setting URL parameters is below. These take the URL to parse as an argument as I wanted to be able to update parameters in linked URLs as well as the current URL which would be provided by window.location

Get URL Parameter

function getUrlParameter(url, parameter) {
    parameter = parameter.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?|&]' + parameter.toLowerCase() + '=([^&#]*)');
    var results = regex.exec('?' + url.toLowerCase().split('?')[1]);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
	
Set URL Parameter

function setUrlParameter(url, key, value) {

    var baseUrl = url.split('?')[0],
        urlQueryString = '?' + url.split('?')[1],
        newParam = key + '=' + value,
        params = '?' + newParam;

    // If the "search" string exists, then build params from it
    if (urlQueryString) {
        var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
        var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');

        if (typeof value === 'undefined' || value === null || value === '') { // Remove param if value is empty
            params = urlQueryString.replace(removeRegex, "$1");
            params = params.replace(/[&;]$/, "");

        } else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it
            params = urlQueryString.replace(updateRegex, "$1" + newParam);

        } else { // Otherwise, add it to end of query string
            params = urlQueryString + '&' + newParam;
        }
    }

    // no parameter was set so we don't need the question mark
    params = params === '?' ? '' : params;

    return baseUrl + params;
}
	

Update

Below is an updated version of the setUrlParameter function which better handles null and URI encoded parameters courtesy of Paul’s comment 🙂

Set URL Parameter

function setUrlParameter(url, key, value) {
	var key = encodeURIComponent(key),
		value = encodeURIComponent(value);

	var baseUrl = url.split('?')[0],
		newParam = key + '=' + value,
		params = '?' + newParam;

	if (url.split('?')[1] == undefined){ // if there are no query strings, make urlQueryString empty
		urlQueryString = '';
	} else {
		urlQueryString = '?' + url.split('?')[1];
	}

	// If the "search" string exists, then build params from it
	if (urlQueryString) {
		var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
		var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');

		if (typeof value === 'undefined' || value === null || value === ") { // Remove param if value is empty
			params = urlQueryString.replace(removeRegex, "$1");
			params = params.replace(/[&;]$/, "");
			
		} else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it
			params = urlQueryString.replace(updateRegex, "$1" + newParam);
			
		} else if (urlQueryString==") { // If there are no query strings
			params = '?' + newParam;
		} else { // Otherwise, add it to end of query string
			params = urlQueryString + '&' + newParam;
		}
	}

	// no parameter was set so we don't need the question mark
	params = params === '?' ? '' : params;

	return baseUrl + params;
}

4 Comments

Paul · 15th January 2019 at 8:24 pm

I hacked a version that can take on more cases (especially those without query strings in the first place). And it also filters the key/value before inserting it… imagine someone puts “Eric & Monica” in their name. Well, you gotta encodeURIComponent that… 🙂

Here is the function. I hope I didn’t make any gross mistakes. Thanks for the basis.

function setUrlParameter(url, key, value) {

var key=encodeURIComponent(key),value=encodeURIComponent(value);

var baseUrl = url.split(‘?’)[0],
newParam = key + ‘=’ + value,
params = ‘?’ + newParam;

if (url.split(‘?’)[1] == undefined){ // if there are no query strings, make urlQueryString empty
urlQueryString =”;
} else {
urlQueryString = ‘?’ + url.split(‘?’)[1];
}

// If the “search” string exists, then build params from it
if (urlQueryString) {
var updateRegex = new RegExp(‘([\?&])’ + key + ‘[^&]*’);
var removeRegex = new RegExp(‘([\?&])’ + key + ‘=[^&;]+[&;]?’);

if (typeof value === ‘undefined’ || value === null || value === ”) { // Remove param if value is empty
params = urlQueryString.replace(removeRegex, “$1”);
params = params.replace(/[&;]$/, “”);

} else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it
params = urlQueryString.replace(updateRegex, “$1″ + newParam);

} else if (urlQueryString==”) { // If there are no query strings
params = ‘?’ + newParam;
} else { // Otherwise, add it to end of query string
params = urlQueryString + ‘&’ + newParam;
}
}

// no parameter was set so we don’t need the question mark
params = params === ‘?’ ? ” : params;

return baseUrl + params;
}

    Shinigami · 16th January 2019 at 4:12 pm

    Thanks for sharing your improved version, I’ve updated the post to include it. Should hopefully spare me some pain in future 🙂

Toadette · 28th January 2019 at 5:03 pm

Quick question, when I try to pass the url into getUrlParameter using window.location, url.toLowerCase() pulls an error saying that function doesn’t exist. Now I’ve tried using url.toString before passing it into the function but that didn’t fix it either. However hard coding the url in ‘ ‘ did work, so I’m not exactly sure what the work around is. Any advice you can give me is greatly appreciated, otherwise your functions have worked wonderfully and helped me a lot thank you.

    Shinigami · 29th January 2019 at 8:06 am

    Hi, glad you’re finding it useful 🙂 The only thing I can see is that you’ve got a comma after window.location rather than a period which could be causing it to fail.

Leave a Reply

Your email address will not be published. Required fields are marked *