用javascript修改日期字符串

我有一些事件将其日期拉如下:

6 月 20 日上午 10 点 - 9 月 5 日晚上 10 点

9 月 28 日中午 - 下午 4 点

我无法控制它返回的内容,所以我需要通过 javascript 删除它

我需要删除时间并将月份替换为 3 个字符的版本,如下所示:

6 月 20 日 - 9 月 5 日

我已经开始这样做了,但我不知道如何删除时间,因为它可以格式化为 AM/PM 或 MIDNIGHT/NOON

这是我到目前为止所做的:


var dateExample = '2nd August 9am - 27th September midnight';

function trimDate(date){

  const dateArray = date.split(' ');

  var months = [['January', 'Jan'], ['February', 'Feb'], ['March', 'Mar'], ['April', 'Apr'], ['May', 'May'], ['June', 'Jun'], ['July', 'Jul'], ['August', 'Aug'], ['September', 'Sep'], ['October', 'Oct'], ['November', 'Nov'], ['December', 'Dec']];


  for (let x = 0; x < months.length; x++){

    let i = dateArray.findIndex(d => d === months[x][0]);

    if (i > -1) dateArray.splice(i, 1, months[x][1]);

  }

  console.log(dateArray.join(' '));

}


trimDate(dateExample);


繁花如伊
浏览 216回答 2
2回答

catspeake

看起来应该可以使用单个正则表达式:const dateExamples = [&nbsp; '2nd August 9am - 27th September midnight',&nbsp; '20th June 10am - 5th September 10pm',&nbsp; '2nd August noon - 27th September midnight']const regex = /[0-9]{1,2}[ndrths]{2}[\s]{1}[\w]{3}/gdateExamples.forEach(dateExample => console.log(dateExample.match(regex).join(' - ')))

qq_笑_17

使用正则表达式可以更简单地替换日期:var dateExample = '2nd August 9am - 27th September midnight';var re = /January|February|March|April|May|June|July|August|September|October|November|December/gi;var replaced = dateExample.replace(re, m => m.substring(0,3));console.log(replaced)您可以使用类似的技巧,正则表达式可能会更复杂一些:var dateExample = '2nd August 9am- 27th September midnight';var datesRegex = /January|February|March|April|May|June|July|August|September|October|November|December/gi;var timesRegex = /\w*([0-9]{1,2}(am|pm|AM|PM))|(noon|midnight)\w*/givar replaced = dateExample.replace(datesRegex, m => m.substring(0,3))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.replace(timesRegex,'');console.log(replaced)把这一切放在一起function clean(input){&nbsp; var datesRegex = /January|February|March|April|May|June|July|August|September|October|November|December/gi;&nbsp; var timesRegex = /\w*([0-9]{1,2}(am|pm|AM|PM)\w*)|(noon|midnight)/gi&nbsp; return input.replace(datesRegex, m => m.substring(0,3))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.replace(timesRegex,'');}// test casesconsole.log(clean("20th June 10am - 5th September 10pm"));console.log(clean("2nd August 9am - 27th September midnight"));console.log(clean("2nd August noon - 27th September midnight"));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript