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?
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?
Share Improve this question edited Mar 28, 2010 at 22:09 Jon Seigel 12.4k8 gold badges60 silver badges93 bronze badges asked Jul 20, 2009 at 16:17 VorinowskyVorinowsky 31 silver badge2 bronze badges3 Answers
Reset to default 4It 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]
You could check to see if the hyphen character exists using mystring.indexOf('-')
(which will return -1 if it doesn't exist). But I'm pretty sure that if you split a string on a character that doesn't contain that character, it will just return the original string.
Why don't you add a hyphen prior to performing the split? You are grabbing the first element anyway. What's the difference if it's the first of two or the first of three elements?
var time_of_year = $((this).attr("id")+'-x').split('-')[0];
That way you are grabbing the item to the left of the first hyphen, and there will always be a first hyphen:
"april-23-x" "springtime-x"
(Note, I didn't test this, and am not staking my life on the syntax! But maybe it'll be a fresh idea for you.)
Edit: By the way, I think the example in the Original Post will work anyway. Split should return a list of length 1, and you are grabbing the [0]'th element, which is perfect.