Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created January 16, 2013 00:55
Show Gist options
  • Save DavidWells/4543685 to your computer and use it in GitHub Desktop.
Save DavidWells/4543685 to your computer and use it in GitHub Desktop.
JavaScript :: Regex trick: Parse a query string into an object
// http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
// JavaScript regex trick: Parse a query string into an object
var queryString = {};
anchor.href.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { queryString[$1] = $3; }
);
// Usage
var uri = 'http://your.domain/product.aspx?category=4&product_id=2140&query=lcd+tv';
var queryString = {};
uri.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { queryString[$1] = $3; }
);
console.log('ID: ' + queryString['product_id']); // ID: 2140
console.log('Name: ' + queryString['product_name']); // Name: undefined
console.log('Category: ' + queryString['category']); // Category: 4
@MarkMYoung
Copy link

Thank you for this, @DavidWells. I changed it to be more like functional programming without a reference outside of the replacer by doing this.

let params = (anchor.search.match( new RegExp("([^?=&]+)(=([^&]*))?", 'g' )) || [])
	.reduce( function( result, each, n, every )
	{
		let[ key, value ] = each.split( '=' );
		result[ key ] = value;
		return( result );
	}, {});```

@craigsh
Copy link

craigsh commented Jun 10, 2020

You'd additionally want to call decodeURIComponent on the key and value parts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment