Search code examples
javascriptjquerystringtokenizerstring-parsing

How to call split(token) on a string that does not contain the token without causing an error?


I have two types of strings as the IDs of elements in my HTML markup:

Dates:

"april-23"
"march-20"

and season names:

"springtime"
"winter"

The dates have a dash separating the month and the day.

The seasons are a single word with no other tokens.

I want to assign the month or the season to a new variable called:

time_of_year

If I do this:

var time_of_year = $(this).attr("id").split('-')[0];

It will work on the months but if I call it on a season name which does not contain the token, will it generate an error?

What's the safe way to do this?


Solution

  • It doesn't return an error but it does return an array with a length of one.

    You could do something like this:

    var splitty = $(this).attr('id').split('-');
    if (splitty.length > 1) {
       time_of_year = splitty[0];
    }
    else {
       // do something else magical here
    }
    

    Here are the docs on split.

    But, if you always want the first value and didn't care about the others, you could just use your original code w/o a problem:

    var time_of_year = $(this).attr('id').split('-')[0]