Sep
2
2011

Get URL Variables with Javascript

Today I needed a quick function to read URL variables in JavaScript.

The code had to be library/framework independent as well as be cross browser compatible.

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

Syntax:
getUrlVars(variableName)

Arguments:
variableName – (string, optional) The variable name to search for.

Returns:
If variable name provided will return the value of the variable (string), if the variable name does not exist will return false (boolean)

If variable name not provided will return an object containing all key/value pairs (object). Note: If no URL variable are present will provided an empty object.


Example 1: (return all URL variables)

	<strong>Example Return all URL vars (see console.log)</strong>
	<script type="text/javascript">
		console.log('All URL Vars');
		console.log(getUrlVars());
		// returns all url variabls in key value pairs OR an empty object if none exist
	</script>

Example 2: (check for existence of a variable and return its value if variable exists)

	<strong>Example Return a specify URL variables' value (see console.log)</strong>
	<script type="text/javascript">
		var myVar = getUrlVars('tim');
		console.log('Getting value of URL variable tim');
		if(myVar) {
			console.log(myVar);
			// returns value of passed variable name or false if it does not exist
		} else {
			console.log('myVar does not exist.')
		}
	</script>

1 Comment + Add Comment

  • Hi mates, its great post regarding tutoringand entirely explained, keep it up all the time.

    Thumb up 2 Thumb down 0

Leave a comment

Show/Hide Footer Actions

Status: Available for your project.