-1

I am trying to get a variable from a URL but it just keep returning null. I have tried to do this so many ways and read multiple tutorials but nothing seems to work. Below is the url.

http://example.com/page2.html?user%20=admin 

and the javascript code I am using to get the variable

var getQueryString = function ( field, url ) {
var href = url ? url : window.location.href;
var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
var string = reg.exec(href);
return string ? string[1] : null;
};

var user = getQueryString('user'); 

document.write (user); 
samw003801
  • 13
  • 3
  • 2
    There is no parameter named `user` in that URL. – CBroe Apr 20 '18 at 10:44
  • 3
    Possible duplicate of [How to obtain the query string from the current URL with JavaScript?](https://stackoverflow.com/questions/9870512/how-to-obtain-the-query-string-from-the-current-url-with-javascript) – Narendra Jadhav Apr 20 '18 at 10:45
  • Possible duplicate of [How to get the value from the GET parameters?](https://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-get-parameters) – Azad Apr 20 '18 at 10:57

2 Answers2

0

Try this let querystring = window.location.search.substring(1);

kish
  • 151
  • 3
  • 16
0

Your regular expression doesn't match due to %20 in the url. Try getting rid of %20 first before applying regular expression check:

var getQueryString = function (field, url) {
    var href = url ? url : window.location.href;

    // get rid of '%20' in url
    href = href.replace(/%20/g, '');

    var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
    var string = reg.exec(href);
    return string ? string[1] : null;
};


var my_url = 'http://example.com/page2.html?user%20=admin';
var user = getQueryString('user', my_url);

document.write (user); 
Shuwn Yuan Tee
  • 5,578
  • 6
  • 28
  • 42