Some JavaScript + REGEX goo to get query strings from your HREF/URI/URL

I guess there is a library somewhere to do this, but I couldn’t find it fast enough so I spit this contraption out. It’s a function that grabs the value from a URI/URL query string. Yes, writing those nasty REGEXs about drove me nuts! ;) Maybe I can save at least one soul out there some trouble. If you see an enhancement option or have ideas, please comment and let me know!

function GiveMeTheQueryStringParameterValue(parameterName) {
    parameterName = parameterName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + parameterName + "=([^&#]*)");
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

2 thoughts on “Some JavaScript + REGEX goo to get query strings from your HREF/URI/URL

    • Oh yeah, instantiating REGEX over and over can easily kill performance. I was just using this as a one shot, but will take a look at those other solutions. thanks!

Comments are closed.