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.

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,''));
}

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


0 Comments

Leave a Reply to Anonymous Cancel reply

Avatar placeholder

Your email address will not be published.