views:

57

answers:

2

Hi,

I'm trying to figure out a way to format a date string that sits inside string using javascript.

The string can be:

"hello there From 2010-03-04 00:00:00.0 to 2010-03-31 00:00:00.0"

or

"stuff like 2010-03-04 20:00:00.0 and 2010-03-31 00:00:02.0 blah blah"

I'd like it to end up like:

"stuff like 4 March 2010 and 31 March 2010 blah blah"

Does anyone have any idea as to how this could be achieved?

A: 

I'd suggest using a regular expression to locate a date string, assuming you know the existing format, and then you can replace it with the formatted version.

Amber
+1  A: 

If the date is always going to be that format, you can replace it using a regular expression:

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
str  = "hello there From 2010-03-04 00:00:00.0 to 2010-03-31 00:00:00.0";
alert(str.replace(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})\:(\d{2}).(\d{1})/g,
    function ($0, $1, $2, $3, $4, $5, $6, $7, $8)
    {
        var date = new Date($1, $2, $3);
        return date.getDate() + " " + months[date.getMonth()] + " " + date.getFullYear();
    })
);

Example at http://jsbin.com/igeti/

Andy E