2017-08-08 32 views
0

有鑑於此:如何將字符串拆分爲相應的對象?

const MATCH_NAME = /\s+([a-z]+)\s+/i; 
 

 
function parseDates(input) { 
 
    const parts = input.split(MATCH_NAME); 
 
    const result = { 
 
    dates: [], 
 
    year: null 
 
    }; 
 

 
    while (parts.length > 2) { 
 
    const [days, month, suffix] = parts.splice(0, 2); 
 
    result.dates.push({ 
 
     month, 
 
     days: days.split(/\D+/), 
 
     suffix 
 
    }); 
 
    } 
 

 
    result.year = parts[0]; 
 
    return result; 
 
} 
 

 
console.log(parseDates('12-5 November 17 May 1954 CE')); 
 
console.log(parseDates('1 January 1976 CE')); 
 
console.log(parseDates('12 22 March 1965'));

year OBJ像1976 CECE應在suffix結束。

好一會:

Month: November 
    Days: 12, 5 
Month: May 
    Days: 17 
Year: 1954 
Suffix: CE 

jsFiddle here

+2

首先,您需要定義所有可能的日期輸入組合。然後匹配那些組合。 – Tschallacka

+0

我的建議,爲字符串使用預先定義的模式 – Rajesh

+0

@Tschallacka這裏列出的日期是定義日期https://stackoverflow.com/questions/45555581/how-to-check-if-numbers-precedes-a- more-verbal-string – downFast

回答

1

在我的理解,你的模式是這樣的:

  • 你必須用空格分隔值的列表。
  • 值可以是數字或字母。
  • 如果數字,
    • 如果<= 31,它一天要推到天陣。
    • 如果大於1,可以用連字符或空格隔開天數。
    • 否則它是年份。
  • 如果字母,
    • 如果隨後一年,長度小於3(假設後綴爲2位數,你可以有不注日期值的日期(例如:「2007年11月「)
    • 否則是月份。

注:如果我的理解是正確的,那麼下面的解決方案將幫助你。如果不是,請分享不一致的地方。

function parseDates(input) { 
 
    var parts = processHTMLString(input).split(/[-–,\/\s]/g); 
 
    var result = []; 
 
    var numRegex = /\d+/; 
 
    var final = parts.reduce(function(temp, c) { 
 
    if (numRegex.test(c)) { 
 
     let num = parseInt(c); 
 
     if (temp.year || (temp.month && num < 31)) { 
 
     result.push(temp); 
 
     temp = {}; 
 
     } 
 
     temp.days = temp.days || [] 
 
     if (c.indexOf("-") >= 0) { 
 
     temp.days = temp.days.concat(c.split("-")); 
 
     } else if (num > 31) 
 
     temp.year = c; 
 
     else 
 
     temp.days.push(c) 
 
    } else if (c.length < 3 && temp.year) { 
 
     temp.suffix = c 
 
    } else { 
 
     temp.month = c; 
 
    } 
 
    return temp; 
 
    }, {}); 
 
    result.push(final); 
 
    return result; 
 
} 
 

 
function processHTMLString(str) { 
 
    var div = document.createElement("div"); 
 
    div.innerHTML = str; 
 
    // This will process `&nbsp;` and any other such value. 
 
    return div.textContent; 
 
} 
 

 
console.log(parseDates('12-5 November 2007 ce 17 May 1954 Ce')); 
 
console.log(parseDates('1 January 1976 CE')); 
 
console.log(parseDates('12 22 March 1965'));

+0

我們添加了'if(temp.year || (temp.month && num <31)&& temp.year> 0){'爲了只在有一個月的時候才推動整個對象,而我們在其他地方檢查實際的單詞是我們的月份之一。 if(months.has(c)){temp.month = c;'給定一組月份'var months = new Set([「January」,「February」,「March」,「April」,「May 「,」六月「,」七月「,」八月「,」九月「,」十月「,」十一月「,」十二月「]);'這樣也會驗證'1988年5月4 - 10日' – downFast