views:

46

answers:

3

I have this string...

var myDate = "November 15, 2010";

.....and I need to do this...

$("#request_showdate_1i").val('2010');
$("#request_showdate_2i").val('November');
$("#request_showdate_3i").val('15');

Any ideas how to break this string up?

+7  A: 

You can for example use a regular expression:

var parts = /(\S+) (\d+), (\d+)/.exec(myDate);
$("#request_showdate_1i").val(parts[3]);
$("#request_showdate_2i").val(parts[1]);
$("#request_showdate_3i").val(parts[2]);
Guffa
Just a suggestion, should you use `/s` instead of literal spaces to make it more flexible?
alex
Can anyone think of a scenario where this would break?
Marko
@Marko: What about day 33? :P ... Of note: Using the Date method a day `33` on November would jump to December 3.
BrunoLM
+3  A: 

You can use the Date object, example on jsFiddle

var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

var d = new Date("November 15, 2010");

$("#request_showdate_1i").val(d.getFullYear());      // 2010
$("#request_showdate_2i").val(months[d.getMonth()]); // November from array
$("#request_showdate_3i").val(d.getDate());          // 15
BrunoLM
+1  A: 

@Guffa's answer seems worth a try, but have you thought about using the datepart features of Javascript?

3 divs to hold the different date parts

<div class="day"></div>
<div class="month"></div>
<div class="year"></div>

And some Javascript magic

var myDate = new Date("November 15, 2010");
var month_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");

$(".day").text(myDate.getDate());
$(".month").text(month_names[myDate.getMonth()]);
$(".year").text(myDate.getFullYear());

Here's a jsFiddle sample.

Marko