Skip to content

Instantly share code, notes, and snippets.

@greyby
Created October 29, 2015 16:31
Show Gist options
  • Save greyby/b4cefafab15966ca4d99 to your computer and use it in GitHub Desktop.
Save greyby/b4cefafab15966ca4d99 to your computer and use it in GitHub Desktop.
get url parameter by name with javascript
var getParameterByName = function (field, url) {
var href = url ? url : window.location.search;
// replace '[' and ']' character for '\[' and '\]'
field = field.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + field + "=([^&#]*)"),
results = regex.exec(href);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
@greyby
Copy link
Author

greyby commented Oct 29, 2015

This function is from stackoverflow.I think it has some problems.It can't handle these urls.

  1. http://example.com/t?a[1[231]=bbb
  2. multiple values
    http://example.com/t?field1=value1&field1=value2&field2=value3
  3. query string's key has reserved words
    http://example.com/t?a+b=bbb

@greyby
Copy link
Author

greyby commented Oct 29, 2015

var getParameterByName = function (field, url) {
     var href = url ? url : window.location.search;
    field = field.replace(/[\[]/g, "\\[").replace(/[\]]/g, "\\]");
    var regex = new RegExp("[\\?&]" + field + "=([^&#]*)"),
    results = regex.exec(href);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment