Last Updated: February 25, 2016
·
702
· 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;
}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside