为了账号安全,请及时绑定邮箱和手机立即绑定

用javascript修改日期字符串

用javascript修改日期字符串

繁花如伊 2021-09-30 14:57:43
我有一些事件将其日期拉如下: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);
查看完整描述

2 回答

?
catspeake

TA贡献1111条经验 获得超0个赞

看起来应该可以使用单个正则表达式:


const dateExamples = [

  '2nd August 9am - 27th September midnight',

  '20th June 10am - 5th September 10pm',

  '2nd August noon - 27th September midnight'

]

const regex = /[0-9]{1,2}[ndrths]{2}[\s]{1}[\w]{3}/g

dateExamples.forEach(dateExample => console.log(dateExample.match(regex).join(' - ')))


查看完整回答
反对 回复 2021-09-30
?
qq_笑_17

TA贡献1818条经验 获得超7个赞

使用正则表达式可以更简单地替换日期:


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*/gi

var replaced = dateExample.replace(datesRegex, m => m.substring(0,3))

                           .replace(timesRegex,'');

console.log(replaced)

把这一切放在一起


function clean(input){


  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)\w*)|(noon|midnight)/gi

  return input.replace(datesRegex, m => m.substring(0,3))

                             .replace(timesRegex,'');

}


// test cases

console.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"));


查看完整回答
反对 回复 2021-09-30
  • 2 回答
  • 0 关注
  • 215 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信