grab query string using javascript [duplicate]

i have a the following url

Now i want to grab the values of num1 and num2 using javascript


var QueryString = function () {
  // This function is anonymous, is executed immediately and 
  // the return value is assigned to QueryString!
  var query_string = {};
  var query =;
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
        // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = pair[1];
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]], pair[1] ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
    return query_string;
} ();


I feel like reaching the get parameters with javascript is kind of mixing up the roles of PHP and javascript so i prefer to do it this way. You can get the URL with window.href and parse but this is better form

Somewhere in PHP body:

echo '<input type="hidden" id="num1_arg" value=" . $_GET['num1'] . '/>';
echo '<input type="hidden" id="num2_arg" value=" . $_GET['num2'] . '/>';

Javascript (ill use jquery, but it can be done without)

n1 = $('#num1_arg').val();
n2 = $('#num2_arg').val();

Try using this simple function:

var parseQueryString = function() {
    var queryString =;
    var pairs = queryString.split("&");
    var params = {};
    for (var i = 0; i < pairs.length; i++) {
        var parts = pairs[i].split("=");
        var key = parts[0];
        var value = parts[1];
        params[key] = value;
    return params;

If num1 and num2 are always in the same order, you can use regular expressions:

var url = ...
var pattern = /num1=(\d*)&num2=(\d*)/
var match = pattern.exec(url)
var num1 = match[1]
var num2 = match[2]


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.