首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将字符串拆分为相应的对象?

如何将字符串拆分为相应的对象?
EN

Stack Overflow用户
提问于 2017-08-08 07:04:26
回答 1查看 68关注 0票数 0

鉴于此:

代码语言:javascript
复制
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中。

试着去:

代码语言:javascript
复制
Month: November
  Days: 12, 5
Month: May
  Days: 17
Year: 1954
Suffix: CE

jsFiddle在这里

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-08 07:56:53

在我看来,你的模式是这样的:

  • 您有一个由空格分隔的值列表。
  • 值可以是数字或字母。
  • 如果数字,
    • 如果是<= 31,则为一天,并应将其推送到days数组。
    • 日可以用连字符或空格分隔,如果超过1。
    • 否则就是一年了。

  • 如果字母,
    • 如果后面是年份,且长度小于3(假设后缀为2位,并且可以有一个没有日期值的日期(例如:“2007年11月”))
    • 否则就是个月了。

注:如果我的理解是正确的,那么下面的解决方案将对您有所帮助。如果没有,请分享不一致之处。

代码语言:javascript
复制
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'));

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45561450

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档