简体   繁体   中英

Use JavaScript to replace a date inside of a string

I am struggling with javaScript replace and dates.

In short, I have a string that has a date inside of it. I need to replace that date with a newly formatted date, while maintaining the string.

var d1 = 'We met on 2014-02-20';
var d2 = 'I saw you again on Thursday, June 05, 2012';
var d3 = 'We had a great day on 2/15/2013';
var d4 = 'On March 07, 2015 we had to go to school';
var d5 = 'The vacation is between 1/1/15 and 1/2/15';

What I need is to get a standard date in all of these lines, but every solution just extracts the date and prints it. The best article I have found involves JQUERY UI [ var dt1 = $.datepicker.formatDate('D, d M yy', new Date(d1)); ], which works great, but it strips the date out of the string and I am left with the date only.

What I am trying to achieve is something like this:

var d1 = 'We met on 2014-02-20';
var d2 = 'I saw you again on Thursday, June 05, 2012';
var d3 = 'We had a great day on 2/15/2013';
var d4 = 'On March 07, 2015 we had to go to school';

TO

print_date_str(d1);

We met on Mon, 20 Feb 2014

print_date_str(d2);

I saw you again on Thu, 05 Jun 2012

print_date_str(d3);

We had a great day on Sun, 15 Feb 2013

print_date_str(d4);

On Fri, 07 Mar 2015 we had to go to school

print_date_str(d5);

'The vacation is between Tue, 01 Jan 2015 and Wed, 02 Jan 2015 '

Here is a JSFIDDLE showing Jquery UI date format: http://jsfiddle.net/k7qrw8o7/1/

Your guidance and help is greatly appreciated.

Here is a good site to reference for formatting JavaScript dates. MS JS time var date = new Date(Date.UTC(2014, 1, 20)); then you would do var d1Date = date.toLocaleDateString("en-US") then var d1 = 'We met on '+ d1Date;

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