I'm working with a f开发者_高级运维unction that outputs a string that is always formatted "Month Day, Year". With this, I'm looking to be able to convert the string into three variables. One for month, one for day, and one for year. The project is jQuery based, so if there is a more elegant solution that way, I would appreciate it.
Update: Here is some of the code that i'm using. Before today, I wrote a function that used select options to choose the month, date, and year. Now I've changed to a simpler solution that uses a single text input in the format "Month Day, Year".
So now when I submit the form, instead of being able to use
var sm = smonth.value;
var sd = sday.value;
var sy = syear.value;
I only have one variable as
var sdate = sdate.value;
And what I'd like to do is be able to convert the sdate value (which is just the Month Day, Year string), back to the sm (Selected Month), sd (Selected Day), and sy (Selected Year) values.
Or some like this:
var sdate = "Month Day, Year";
sdate = sdate.split(" ");
var sm = sdate[0];
var sd = sdate[1].substr(0, sdate[1].length-1);
var sy = sdate[2];
use the javascript string functions.
var test = "Jan 21, 2011";
var firstbreak = test.indexOf(" ");
var secondbreak = test.lastIndexOf(" ");
var month = test.substr(0, firstbreak);
var day = test.substr(firstbreak + 1, secondbreak - firstbreak-2);
var year = test.substring(secondbreak + 1);
alert(month + " " + day + ", " + year);
Use String.split(' ')
, or a RegExp.
var aMatches = sdate.match(/^\b(\w+)\b (\d+), (\d+){2,4)$/gi);
精彩评论