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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s