Skip to content

Instantly share code, notes, and snippets.

@reicolina
Last active July 12, 2016 16:32
Show Gist options
  • Save reicolina/f6d1838dbaf75e93b8b4d03779a913eb to your computer and use it in GitHub Desktop.
Save reicolina/f6d1838dbaf75e93b8b4d03779a913eb to your computer and use it in GitHub Desktop.
A Javascript method to get a query string value from a given URL

The following Javascript method takes a query parameter and the URL it belongs too, and it returns the value associated with that query parameter.

function getQueryStringValue(param, url) {
  if (!url) {
      // handle null or undefined
  	return null;
  }
  var regex = new RegExp("[?&]" + param + "(=([^&#]*)|&|#|$)");
  var results = regex.exec(url);
  if (!results) {
  	// if no match then the param passed in doesn't exist in the query,
  	// so return null
  	return null;
  }
  // If the match succeeds, the exec() method returns an array that
  // has the matched text as the first item (0), and then one item
  // for each capturing parenthesis (1 and 2) that matched, containing
  // the text that was captured. In this case we are looking for the
  // text captured in the second capturing parenthesis (2)
  var value = results[2];
  if (!value) {
  	// the param exist within the query but it has no value,
  	// so return an empty string
  	return '';
  }
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

How to use it:

var url = 'www.myapp.com/users/?firstName=Bob&lastName=Smith&age=35';
var lastName = getQueryStringValue('lastName', url); // Smith
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment