-1

I will have a URL like this:

http://website/index.html?id=1234&type=something

The id and type being passed will be different depending on what the user does on the other end.

Using Javascript, I want to get the id and the type to be used as variables, like this:

var theID = 1234
var theType = something

But I don't know how to pull those values from the URL and set the values like above. How can I do this?

ZeekLTK
  • 233
  • 2
  • 9
  • Duplicate: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values – DarkBee Oct 31 '13 at 14:34
  • 1
    http://papermashup.com/read-url-get-variables-withjavascript/ – davibq Oct 31 '13 at 14:35
  • @davibq - thanks, that's perfect for what I need. I don't want to pass any values into the function, and this code pulls it directly from the URL. Thanks! – ZeekLTK Oct 31 '13 at 15:04

2 Answers2

2

Try this

function qs(url, key) {
    var vars = [], hash;
    var hashes = url.slice(url.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[key];
}

var url = YourUrl;
alert(qs(url,'id'));

DEMO

Satpal
  • 132,252
  • 13
  • 159
  • 168
1

My util function, its a bit dirty but gets the job done. No need to split array just few indexOf functions. If you want to utf8 decoded value use decodeURIComponent(str) or iso1 legacy decoded use decodeURI(str)

// parse parameter value from url (case sensitive)
function getURLParam(strURL, strKey) {
   // http://mywebapp/do.url?key1=val1&key2=val2
   var idx = strURL.indexOf('?');
   if (idx < 0) return ""; // no params

   // "&key1=val1&key2=val2&"
   strURL = "&" + strURL.substring(idx+1) + "&";
   idx = strURL.indexOf("&" + strKey + "=");
   if (idx < 0) return ""; // param not found

   // "&key1=val1&key2=val2&" -> "val1&key2=val2&" -> "val1"
   strURL = strURL.substring(idx + strKey.length + 2);
   idx = strURL.indexOf("&");    
   return strURL.substring(0, idx);
}
Whome
  • 10,181
  • 6
  • 53
  • 65