Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get query string parameter in Javascript or jQuery?

I have a link like this:

http://localhost:8162/UI/Link2.aspx?txt_temp=123abc

I want to get the value 123abc . I have followed this How can I get query string values in JavaScript? and jquery get querystring from URL

$(document).ready(function () {
    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    onload = function () {
        alert(getParameterByName('txt_temp'));
        alert(getUrlVars()["txt_temp"]);
    }  
});

But it does not work.

like image 513
Headshot Avatar asked Dec 01 '22 14:12

Headshot


1 Answers

Suppose you have URL with many params eg:-

"http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"

Then in js you can do like:

var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"

OR

var url = window.location.href

then split main url like:

hashes = url.split("?")[1]

//hashes holds this output "txt_temp=123abc&a=1&b=2"

Then again you can split by & to get individual param

EDIT

Check this example:

function getUrlVars() {
var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2";
var vars = {};
var hashes = url.split("?")[1];
var hash = hashes.split('&');

for (var i = 0; i < hash.length; i++) {
params=hash[i].split("=");
vars[params[0]] = params[1];
}
return vars;
}

Output

getUrlVars()
Object {txt_temp: "123abc", a: "1", b: "2"}
like image 160
Abhi Avatar answered Dec 04 '22 02:12

Abhi