5

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.

Community
  • 1
  • 1
Headshot
  • 423
  • 1
  • 6
  • 22

7 Answers7

11

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"}
Abhi
  • 4,123
  • 6
  • 45
  • 77
  • 1
    Dear Abhi, As you say , it look like ``` function getUrlVars() { var url = window.location.href; var vars = [], hash; var hashes = url.split("?")[1]; for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } alert(getUrlVars()["txt_temp"]); ``` – Headshot May 16 '15 at 03:32
  • Define like `var vars = {}` then `vars[hash[0]] = hash[1]` – Abhi May 16 '15 at 03:40
  • Oh no, It's seem not work. ```function getUrlVars() { var url = window.location.href; var vars = [], hash; var hashes = url.split("?")[1]; for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash); vars[hash[0]] = hash[1]; } return vars; } alert(getUrlVars()["txt_temp"]); alert(getUrlVars()["a"]);``` – Headshot May 16 '15 at 04:04
  • You are still defining `vars = []`, instead use `vars = {}` then try – Abhi May 16 '15 at 04:05
  • Did you try it ? I think it's not working . `function getUrlVars() { var url = window.location.href; var vars = {}, hash; var hashes = url.split("?")[1]; for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('&'); vars.push(hash); vars[hash[0]] = hash[1]; } return vars; } alert(getUrlVars()["txt_temp"]); alert(getUrlVars()["a"]);` It's not working.Thank guys. – Headshot May 16 '15 at 06:59
  • I don't understand why you have selected a correct answer above when you are still in middle of your problem. Please check the updated answer. – Abhi May 16 '15 at 07:51
  • Ok, I want to understand more, knowledge is always infinite . Thank sir. – Headshot May 16 '15 at 09:27
  • The functions you already had were completely alright, weren't they? The only problem was that they weren't executing... In any case, if this is the answer, you should remove the onload bit from your question and point out why the functions you originally had didn't work, so this question is useful for further visitors. –  May 16 '15 at 09:35
5

It doesn't work because you're running the functions inside of onload, which doesn't fire inside of document.ready, because by the time the code inside of document.ready executes, onload has already fired. Just get your code out of the onload event:

http://jsfiddle.net/whp9hnsk/1/

$(document).ready(function() {

   // Remove this, this is only for testing.
   history.pushState(null, null, '/UI/Link2.aspx?txt_temp=123abc');

   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, " "));
   }

   // You may also place this inside of a function,
   // and execute it when you desire, but `onload` is not going
   // to fire by itself, when inside of document.ready
   alert(getParameterByName('txt_temp'));
   alert(getUrlVars()["txt_temp"]);

});
2

This should get you started:

function parseQueryStr( str, obj ) {


    // Return object
    obj = obj || {};


    // Looping through our key/values
    var keyvalues = str.split('&');
    for( var i=0; i<keyvalues.length; i++ ) {


        // Break apart our key/value
        var sides = keyvalues[i].split( '=' );


        // Valid propery name
        if( sides[0] != '' ) {


            // Decoding our components
            sides[0] = decodeURIComponent( sides[0] );
            sides[1] = decodeURIComponent( sides.splice( 1, sides.length-1 ).join( '=' ) );


            // If we have an array to deal with
            if( sides[0].substring( sides[0].length - 2 ) == '[]' ) {
                var arrayName = sides[0].substring( 0, sides[0].length - 2 );
                obj[ arrayName  ] = obj[ arrayName  ] || [];
                obj[ arrayName ].push( sides[1] );
            }


            // Single property (will overwrite)
            else {
                obj[ sides[0] ] = sides[1];
            }
        }
    }


    // Returning the query object
    return obj;
}

var href = window.location.href.split('#');
var query = href[0].split('?');
query.splice(0,1);
var get = parseQueryStr(query.join('?'));

alert( get.txt_temp );
Blake A. Nichols
  • 870
  • 1
  • 6
  • 11
2

You can use:

    var param = new URLSearchParams(urlString).get('theParamName');

Or if searching the current page:

    var param = new URLSearchParams(location.search).get('theParamName');
aabiro
  • 3,842
  • 2
  • 23
  • 36
0

you have to slice the everything before and after "=" so first answer is a bit incomplete. Here is the answer which works for querystrings includes "=" in it too :) Like:

https://localhost:5071/login?returnUrl=/writer/user?id=315&name=john

Thanks to user abhi

var getUrlVars = function () {
        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]); //to get name before =
            vars[hash[0]] = hashes[i].slice(hashes[i].indexOf('=') + 1); //to take everything after first =
        }
        return vars;
    }

and then get it with

var url = window.getUrlVars()["returnUrl"];

so it will extract "/writer/user?id=315" with "=" too :)

Umut Bebek
  • 364
  • 4
  • 9
-1

I wrote this one liner with ES6 syntax which follows the method of the accepted answer.

function getParam(key){
    return window.location.href.split('?')[1].split('&').filter(x=>x.split('=')[0]==key)[0].split('=')[1];
}

Use:

Lets say the current URL is: https://stackoverflow.com?question=30271461

getParams('question') //30271461
Roy
  • 1,939
  • 1
  • 14
  • 21
-1
interface IQueryParam {
  [key: string]: string;
}


export const getParmFromUrl = () => {
  const url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  const urlParams: IQueryParam = {};
  for (let i = 0; i < url.length; i++) {
    const paramInfo = url[i].split('=');
    urlParams[paramInfo[0]] = paramInfo[1];
  }
  return urlParams;
};
ak000ay
  • 18
  • 4