繁体   English   中英

Js 返回字符串上的开始日期和结束日期

[英]Js return the start date and end date on a string

我有这样的字符串:

(Feb 28-Mar 1)
(Mar 2-3)

我希望我返回一个 object,如下所示,有人可以给我一些建议,我该怎么做?

 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
}
]

我会先删除括号,然后按/[ -]/拆分。 这样你就可以在这两个 forms 之一中得到一个数组

["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]))

我建议使用正则表达式模式来解析每个跨度。

由此我们可以得到 startMonth、startDay、endMonth、endDay。 然后我们可以创建一个getMonthNumber() function 将缩写的月份名称(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 = /\(([az]{3})\s+(\d{1,2})\-([az]{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; }

你可以试试这个

 function rangeCalcFunc(range = null) { if(range && range.length){ const [start, end] = range.substring(1, range.length-1).split("-"); console.log(start);console.log(end); const [startMon, startDt] = start.split(" "); const [endMon, endDt] = end.split(" "); return [ { month: calcMonthInNumber(startMon.trim()), date: startDt }, { month: calcMonthInNumber(endMon.trim()), date: endDt } ] } } function calcMonthInNumber(month) { switch(month.toLowerCase()){ case 'jan': return '01' case 'feb': return '02' //add for other months default: break; } } console.log(rangeCalcFunc("(Jan 28-Feb 1)"));

首先,我们将为月份创建一个映射器。 像这样:

let MonthsMapper = new Map([['Jan', 1], ['Feb', 2], ['Mar', 3] /*...*/])

然后我们需要一个 function,它通过删除括号并用连字符将其拆分来将字符串分割成块。 第一个块是开始日期和结束日期。 有了这两个日期我们就可以进一步得到开始月份、开始日期、结束月份和结束日期。 (通过空格分割我们的块)

从您的示例中我只能看到一种特殊情况,即结束日期未指定月份的情况,在这种情况下它隐含为开始月份。

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),
       }
  ]
}

除了代码之外,这种方法的优点是,如果输入类似于Jan 1-3-Mar 7 ,它就可以工作,而所有其他答案都没有考虑到这一点,因此返回undefined或错误。

简单的正则表达式和月份列表应该可以工作,对我来说这似乎是最直接的。 使用String.prototype.match我们可以“忽略”所有额外的数据(即月份之间的括号和破折号),只提取必要的数据:

 function rD(str) { // have a list of the numbers of each month const monthNum = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 }; // regex to extract the patterns "Feb 23" or "Aug 15-23" let spl = str.match(/[az]{3} \d{1,2}(\-\d{1,2})?/gi); // loop through matches const result = spl.map(s => { // first 3 letters is the month; get the month number const month = monthNum[s.substr(0, 3).toLowerCase()], rest = s.substr(4); // get the rest of the string sans the month and extra space const e = rest.split("-"); return e.map(q => ({ month, day: +q })); }).flat(); // our array may occasionally be multidimensional if the user provides something like "Nov 7-12". We flatten the array to fix that return result; } console.log("(Feb 28-Mar 1):", rD("(Feb 28-Mar 1)")); console.log("(Mar 2-3):", rD("(Mar 2-3)")); console.log("(Nov 7-12-Dec 15):", rD("(Nov 7-12-Dec 15)"));
 .as-console-wrapper { min-height: 100%;important; }

在下面的代码片段中添加了内联的所有步骤。

 // const str = "(Feb 28-Mar 1)"; const str = "(Mar 2-3)"; // An Object which contains numeric value of months. const monthMap = { Jan: 1, Feb: 2, Mar: 3 }; /** * convertStringToObject() method used to convert the input string into an object. * @param: inputString */ function convertStringToObject(inputString) { // Removing open and closed paranthesis and splitting the inputString with '-' const split = inputString.replace('(', '').replace(')', '').split('-'); // If splitted array element does not contain month, appending that. split[1] = (split[1].trim().length === 1)? split[0].split(' ')[0] + ' ' + split[1]: split[1]; // Looping over the splitted array and then creating the object with keys 'month' and 'day' return split.map((item) => { const splittedItem = item.split(' '); return { month: monthMap[splittedItem[0]], day: Number(splittedItem[1]) } }); } // Calling the convertStringToObject() method by passing the input string as a param. console.log(convertStringToObject(str));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM