Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a variable from url parameter using Javascript

Tags:

javascript

url

I am trying to get a url value using javascript, so far I can only get pure numbers, not mixed numbers with letters or just letters. I can't find any working examples of a function that allows for numbers with letters to be retrieved, just numbers. I am not using any non alphanumeric characters. An example value that I am trying to pass is "42p316041610751874cm83p2306600132141".

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;
}

 var first = getUrlVars()["test"];

Any help would be great. Thanks.

like image 348
cWoolf Avatar asked Dec 10 '11 22:12

cWoolf


2 Answers

Here is a condensed version of two of the answers above :

function gup (name) {
  name = RegExp ('[?&]' + name.replace (/([[\]])/, '\\$1') + '=([^&#]*)');
  return (window.location.href.match (name) || ['', ''])[1];
}

Easier to type, easier on processing and, IMHO easier to read. YMMV

like image 184
HBP Avatar answered Sep 19 '22 11:09

HBP


I use this function, and it rocks. I don't remember from where I took it, but it's a good one:

function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
} 

If you have a URL like http://www.exmaple.com/path?p1=lkjsd234&p2=klsjd987, you can use:

alert(gup('p1')); // shows 'lkjsd234';
like image 36
Saeed Neamati Avatar answered Sep 19 '22 11:09

Saeed Neamati