简体   繁体   中英

How do I parse content with regular expression using jQuery?

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?

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

Use String.match()

$dec = "-35:48:00";
matches = $dec.match(/-*[0-9]+/g);
for (i=0;i<matches.length;i++){
  alert(matches[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM