2 回答
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(' - ')))
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"));
添加回答
举报