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

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

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 (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;
}

11 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 🙂

    Mansur Ali Koroglu · 16th January 2020 at 9:35 am

    It seems this also has bugs.

    First: testkey1 testval1
    Second: testkey testval

    Second key will override the first one.

      Shinigami · 17th January 2020 at 2:59 pm

      Thanks for pointing this out, there was a missing “=” in the replacement regex that was making it too greedy, I’ve updated the code now.

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.

Dylan · 29th August 2019 at 12:44 am

In your ‘updated version’, there are typos with the quotes (urlQueryString==”) and urlQueryString is undefined

    Shinigami · 29th August 2019 at 9:50 am

    Good spot, not sure what happened there but I’ve updated now. Thanks!

. · 4th January 2020 at 5:38 am

In case you never figured this out, you should pass window.location.href (a string), and not window.location (an object, which doesn’t have a toLowerCase () function)

J · 13th February 2020 at 9:50 pm

How can I pass all those parameters on to link now? NEXT

Thanks

    Shinigami · 14th February 2020 at 10:05 am

    You can just use something like this.

    var newUrl = setUrlParameter(‘https://blog.bitscry.com’, ‘paramaterName’, ‘paramaterValue’);

Leave a Reply to Mansur Ali Koroglu Cancel reply

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


Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: `POST https://dc.services.visualstudio.com/v2/track` resulted in a `400 Invalid instrumentation key` response: {"itemsReceived":1,"itemsAccepted":0,"errors":[{"index":0,"statusCode":400,"message":"Invalid instrumentation key"}]} in D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113 Stack trace: #0 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Middleware.php(66): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response)) #1 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\promises\src\Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response)) #2 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\promises\src\Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\P in D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line 113