0

I imagine this is really simple but I just seem unable to achieve it. I have this snippet...

var choice = location.href.split("?")[1].split("=")[1];

It works fine until 'choice' is empty, then it throws the following error....

TypeError: location.href.split(...)[1] is undefined

I understand this is because you cant call split on a variable that is undefined, my solution i think is to store the variable and then split it if full or ignore it if undefined.

Can someone help me do this?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

3 Answers3

3

Not super cool to do it like this, but if you expect only one parameter in query string you can do it like this:

var choice = (location.href.split("?")[1] || '').split("=")[1];

You will get choice as undedfined if it's not set in query string.

dfsq
  • 191,768
  • 25
  • 236
  • 258
1

There isn't enough info, but either the attribute href, of the 1 index of the first split is undefined, or the second item of the last split is undefined.

You would separate the split out into several statements.

var choice;
var firstSplit = location.href;

if (firstSplit) {
    var secondSplit = firstSplit.split("?");
}
if (secondSplit[1]) {
    choice = secondSplit[1].split("=");
}

Then you could use whatever returned from the last split.

colin-higgins
  • 1,087
  • 10
  • 14
0

You would see this exception if you are attempting to split apart a URL that may or may not have a querystring. You should check that the querystring exists before attempting to manipulate it:

var choice;
var outerSplit = window.location.href.split('?');
var innerSplit;
if (outerSplit.length > 1) {
    innerSplit = outerSplit.split('=');
    if (innerSplit.length > 1) {
        choice = innerSplit[1];
    }
}

If you find yourself performing this type of querystring manipulation often, you might want to invest in a reusable function like the one from this question.

Community
  • 1
  • 1
jbabey
  • 45,965
  • 12
  • 71
  • 94