Last Updated: February 25, 2016
·
511
· jonlunsford

Parse query strings in javascript

Not a super robust solution but works for simple parsing. My use case for this has been to track and parse referrers, and check for modified query params.

This function accepts a varName (the name of the param you want the value of), and the string to search.

function parseQueryString(varName, queryStr) {
    var queryStr = unescape(queryStr) + '&',
        regex = new RegExp('.*?[&\\?]' + varName + '=(.*?)&.*'),
        val = queryStr.replace(regex, "$1");

    return val == queryStr ? 0 : val;
}