views:

423

answers:

4

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?

+3  A: 

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.

inkedmn
+3  A: 

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]
seth
The length check seems absolutely unnecessary. $(this).attr("id").split('-')[0] alone is safe.
Ates Goral
@Ates I thought about that but it seemed like the OP wanted to do something different if the split character wasn't there. I'll update the answer with this feedback though.
seth
A: 

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.

Kind of a backwards ass way of doing it :P
micmcg
well, admittedly, the "correct" way to do it is to read the documentation and understand how .split() works. But who has time for that, sometimes. So if you're worried about an error, take a quick prophylactic measure, and move forward. Reducing human labor time is a valid goal.Say there's a high school guy, not so knowledgeable about sex, in the back seat of the car with a hottie. He's worried that his finger might get the girl pregnant. Does he stop everything and read the documentation on sex? naaah. you put a condom on your finger and move on. Or better yet, you "ahh, f--k it". :)
A: 

I think what Vorinowsky has is fine.