The easy way to parse query strings



Steven Benner (see his blog) posted this killer regex trick below to simplify parsing query strings in javascript. Brilliant work!

Here’s how to use it in a trigger.

Author: Matt Cauthorn, ExtraHop Networks, Inc.
Title: Query String Parser
Description: Parses your query strings, for the win.
var qstring = HTTP.query;
if(qstring !== null) {
   var qs = {};
   // Parse query string FTW.
   var regex = new RegExp("([^?=&]+)(=([^&]*))?", "g");
   qstring.replace(regex, function($0, $1, $2, $3) { qs[$1] = $3; });
 } else {
// decode the URI for clean keys.
qs.r = decodeURIComponent(qs.r);

Now, to access the values of your query string keys, just use normal javascript property ‘dot’ notation to access them. For example if you have a query string key/value of ‘somekey=myvalue’, access it like:

log(qs.somekey); // this will log 'myvalue'

And, as they say, Bob’s your uncle :slight_smile: