views:

159

answers:

2

I am trying to use jQuery to break right ascension and declination data into their constituents (hours, minutes, and seconds) and (degrees, arc-minutes, and arc-seconds), respectively from a string and store them in variables as numbers. For example:

$dec = "-35:48:00" -> $dec_d = -35, $dec_m = 48, $dec_s = 00

Actually, the data resides in a cell (with a particular class ('ra')) in a table. At present, I have gotten this far:

var $dec = $(this).find(".ra").html();

This gives me the declination as a string but I cannot figure out how to parse that string. I figured out the regular expression (-|)+\d+ (this gives me -35 from -35:48:00) to get the first part. How do I use that in conjunction with my code above?

+3  A: 

This should do it:

var dec = '-35:48:00';
var parts = dec.split(':');

parts[0] would then be -35, parts[1] would be 48, and parts[2] would be 00

You could run them all through parseInt(parts[x], 0) if you want integers out of the strings:

var dec_d = parseInt(parts[0], 10);
var dec_m = parseInt(parts[1], 10);
var dec_s = parseInt(parts[2], 10);

I should point out this really has nothing to do with jQuery and is a Javascript problem (past getting the values out of the HTML document, at least) - The practice of prefixing a variable with a $ is usually done to signify that the variable contains a jQuery collection. Since in this situation it contains HTML, it is a little misleading

Paolo Bergantino
Plus parseInt, of course. :)
Andrew Noyes
Let me finish! :)
Paolo Bergantino
Thank you. This worked perfectly.
Kamal
+1  A: 

Use String.match()

$dec = "-35:48:00";
matches = $dec.match(/-*[0-9]+/g);
for (i=0;i<matches.length;i++){
  alert(matches[i]);
}
Flavius Stef
Thank you! I tested this and it works as well, but the first solution suits my needs better. Too bad I cannot mark both answers as correct.
Kamal