grab query string using javascript [duplicate]

i have a the following url

http://www.test.com/index.html?num1=123&num2=321

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

Answers:

Answer
var QueryString = function () {
  // This function is anonymous, is executed immediately and 
  // the return value is assigned to QueryString!
  var query_string = {};
  var query = window.location.search.substring(1);
  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 {
      query_string[pair[0]].push(pair[1]);
    }
  } 
    return query_string;
} ();


alert(QueryString.num1);
Answer

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();
Answer

Try using this simple function:

var parseQueryString = function() {
    var queryString = window.location.search.substring(1);
    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;
};
Answer

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]

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.