本文介绍了如何将字符串拆分为相应的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为此:
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 CE
,而CE
应该在suffix
中.
The year
obj ends up like 1976 CE
while CE
should be in the suffix
.
试图到达:
Month: November
Days: 12, 5
Month: May
Days: 17
Year: 1954
Suffix: CE
推荐答案
据我了解,您的模式是这样的:
In my understanding, your pattern is something like this:
- 您有一个用空格分隔的值列表.
- 值可以是数字或字母.
- 如果是数字,
- 如果为
<= 31
,则为一天,应将其推入天数组. - 如果日期超过1,则可以用连字符或空格分隔.
- 否则是一年.
- You have a list of values separated by spaces.
- Values can be numeric or alphabets.
- If Numeric,
- If
<= 31
, its a day and should be pushed to days array. - Days can be separated by hyphens or space, if more than 1.
- Else it is year.
- 如果后跟年份,并且长度小于3(后缀为2位数字,并且您可以使用不带日期值的Date(例如:"2007年11月"))
- 否则是月.
注意:如果我的理解是正确的,那么以下解决方案将为您提供帮助.如果没有,请分享不一致之处.
Note: If my understanding is correct, then following solution will help you. If not, please share inconsistencies.
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 ` ` 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'));
这篇关于如何将字符串拆分为相应的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- If
- 如果为