How to get query string values in JavaScript

Hi, Getting query string value in Php is easy you can use global variable like $_GET, $_POST, $_REQUEST. But in case of JavaScript. How you can get it. Here is a simple method you can use to get the value of a query string with JavaScript:

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


Use

// query string like : http://www.xyz.com/?location=lorem&city=&ipsum
  var location = getParameterByName('location'); // "lorem"

Leave a Reply

Your email address will not be published. Required fields are marked *

16 + three =