0

I have the following code to trim an URL to check if a parameter exists. For example if the URL is http://localhost:3000/page?name=jack?number=2000, then the code should have subString as 2000. There could be cases where the number parameter does not exist in the URL.

var url = window.location.href;
var subString = url.substring(url.lastIndexOf('number=') + 7);

alert(subString);
alert(subString.length);

if (subString.length <= 0) {
    //logic here
}

This is not working as expected. For whatever reason, when the number parameter is not in the URL, subString becomes the full URL. However, when there is a number, then it works fine. How do I fix this?

kevin_b
  • 803
  • 4
  • 16
  • 34
  • Possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – tanmay Apr 27 '17 at 05:47
  • try `var substring = location.search && location.search.match(/\d+/) ` – gurvinder372 Apr 27 '17 at 05:50
  • Please look at this link. http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – sridhar Apr 27 '17 at 05:51
  • You're going about this the wrong way. You should really parse the query string, do whatever it is you need to and re-build it from there. Don't treat it like just any string. – Brad Apr 27 '17 at 05:59

2 Answers2

1

I would use the method below, it meets your further fetching variables from querystring

Function

var getUrlParams = function()
        {
            var match,
            pl = /\+/g,  // Regex for replacing addition symbol with a space
            search = /([^&=]+)=?([^&]*)/g,
            decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
            query = window.location.search.substring(1);

            var urlParams = {};
            while (match = search.exec(query))
                urlParams[decode(match[1])] = decode(match[2]);

            return urlParams;
        }

Usage

var param = getUrlParams();
var number = param["number"];
ibubi
  • 2,469
  • 3
  • 29
  • 50
0

First check indexOf number= in the present URL. if it returns -1 means number parameter is not available in the URL.

DEMO with number parameter :

var url = "http://localhost:3000/page?name=jack?number=2000";
if(url.indexOf('number=') != -1) {
var subString = url.substring(url.lastIndexOf('number=') + 7);
alert(subString);
alert(subString.length);
} else {
  alert("no number param");
}

DEMO without number parameter :

var url = "http://localhost:3000/page?name=jack";
if(url.indexOf('number=') != -1) {
var subString = url.substring(url.lastIndexOf('number=') + 7);
alert(subString);
alert(subString.length);
} else {
  alert("no number param");
}
Debug Diva
  • 26,058
  • 13
  • 70
  • 123