fightstarr20
fightstarr20

Reputation: 12588

Javascript error - Can't run .split on undefined

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?

Upvotes: 0

Views: 2362

Answers (3)

dfsq
dfsq

Reputation: 193261

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.

Upvotes: 3

jbabey
jbabey

Reputation: 46647

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.

Upvotes: 0

colin-higgins
colin-higgins

Reputation: 1117

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.

Upvotes: 1

Related Questions