Get query string values from JavaScript

I found this code a while ago, probably somewhere on Stack Overflow, and it’s served me well ever since. It returns a data object filled with the key-value pairs of the query string.

This is a pretty simple function, but if you’re not familiar with regular expressions in JavaScript it might be a little unclear at first.

The RegEx used here matches anything formatted like a query string, capturing both the key and the value. By using parenthesis it creates two subgroups as well. Rather than implementing named groups, JavaScript just treats every set of parenthesis as a group, and numbers them sequentially.

The exec() method will execute the RegEx that called it on the string passed as an argument, and returns each match it encounters one-at-a-time. The matches are returned as arrays, where the [0] index is the full match, and each successive index contains the value of the next parenthetical group. Once it runs out of matches it will return null, which ends the while loop and allows the function to return the values it’s collected.

Try it!

http://www.bendemeyer.com/?

Returned Values:
Tagged with:
Posted in Custom Library Functions, JavaScript, Try It

Leave a Reply

Your email address will not be published. Required fields are marked *

*