我有这样的条件:
(Feb 28-Mar 1)
(Mar 2-3)我想要我返回一个对象,如你可以看到的,有人给我一些建议,我能做什么?
function rD(text){
let date = text.replace('(', '').replace(')', '').split(' ');
//const [start, end] = date[2].split("-").map(Number);
return date;
}
console.log(rD("(Feb 28-Mar 1)"))
console.log(rD("(Mar 2-3)"))
返回:
[
{
month: 2,
day: 28
},
{
month: 3,
day: 1
}
]
[
{
month: 3,
day: 2
},
{
month: 3,
day: 3
}
]发布于 2022-03-02 08:05:14
我首先删除括号,然后按/[ -]/拆分。这样,您就可以在这两种表单中获得一个数组。
["Feb", "28", "Mar", "1"]或
["Mar", "2", "3"]现在,如果数组有4个元素,那么第一个和第三个总是月份,第二个和第四个就是日期。如果数组有3个元素,第一个是一个月的开始和结束,第二个和第三个是日子。
要获得月数,您可以进行简单的查找,如
{ Jan:1, Feb:2, ... }
let months = { Jan: 1, Feb: 2, Mar: 3 /* you get the idea*/}
let spans = ["(Jan 28 - Feb 3)", "(Mar 1-3)"]
let parse = (span) => {
let parts = span.replace(/[()]/g, "").split(/[ -]/).filter(x => !!x);
switch (parts.length) {
case 4: return [{month: months[parts[0]], date: +parts[1]}, {month: months[parts[2]], date: +parts[3]}];
case 3: return [{month: months[parts[0]], date: +parts[1]}, {month: months[parts[0]], date: +parts[2]}];
default: return undefined;
}
}
console.log(parse(spans[0]));
console.log(parse(spans[1]))
发布于 2022-03-02 08:28:38
我建议使用regex模式来解析每个跨度。
由此我们可以得到startMonth,startDay,endMonth,endDay。然后,我们可以创建一个getMonthNumber()函数来转换缩写的月份名称(Jan、Feb等)。给一个数字。
function getMonthNumber(month) {
const lookup = { jan: 01, feb: 02, mar: 03, apr: 04, may: 05, jun: 06, jul: 07, aug: 08, sep: 09, oct: 10, nov: 11, dec: 12};
return lookup[(month + '').toLowerCase()]
}
function parseSpan(str) {
const pattern = /\(([a-z]{3})\s+(\d{1,2})\-([a-z]{3})?\s?(\d{1,2})\)/i
const [, startMonth, startDay, endMonth, endDay] = str.match(pattern);
return [
{ month: getMonthNumber(startMonth), day: +startDay },
{ month: getMonthNumber(endMonth || startMonth), day: +endDay }
];
}
let testInputs = [
'(Feb 28-Mar 1)',
'(Mar 2-3)',
'(Sep 28-Oct 31)',
'(Jan 3-17)'
]
testInputs.map(parseSpan).forEach(span => console.log(span)).as-console-wrapper { max-height: 100% !important; }
发布于 2022-03-02 08:23:38
首先,我们将为这几个月创建一个映射器。就像这样:
let MonthsMapper = new Map([['Jan', 1], ['Feb', 2], ['Mar', 3] /*...*/])然后,我们需要一个函数,通过去掉括号并用连字符将字符串分割成块。第一部分是开始日期和结束日期。有了这两个日期,我们可以进一步获得开始月、开始日、结束月和结束日。(将我们的块分割成白色空间)
从您的示例中只能看到一种特殊情况,那就是当结束日期没有指定一个月时,在这种情况下,它是隐式的开始月份。
let DateObjectParser = (dateString) => {
const [startDate, endDate] = dateString.replace(/[()]/g, '').split('-')
const [startMonth, startDay] = startDate.split(' ')
let [endMonth, endDay] = endDate.split(' ')
// in case a second month is not provided
if (endDay === undefined) {
endDay = endMonth
endMonth = startMonth
}
return [
{
month: MonthsMapper.get(startMonth),
day: parseInt(startDay),
},
{
month: MonthsMapper.get(endMonth),
day: parseInt(endDay),
}
]
}https://stackoverflow.com/questions/71319144
复制相似问题