【问题标题】:Trying to match the year in a string in javascript试图在javascript中匹配字符串中的年份
【发布时间】:2018-12-20 23:41:44
【问题描述】:

我希望能够获取一个字符串数组:

这是我正在使用的模拟数据。

const archives = {
    "data": [{
            "id": 1,
            "type": "archive",
            "attributes": {
                "name": "Employee Engagement Summary",
                "description": "Report description goes here",
                "creation_date": "March 21, 2018",
                "date_range": "03/01/2018-05/15/2018",
                "data_sets": "Facility A, Nursing Department"
            }
        },
        {
            "id": 1,
            "type": "archive",
            "attributes": {
                "name": "Sample Survey 1",
                "description": "Report description goes here",
                "creation_date": "March 21, 2017",
                "date_range": "03/01/2017-05/15/2017",
                "data_sets": "Facility A, Nursing Department"
            }
        },
        {
            "id": 1,
            "type": "archive",
            "attributes": {
                "name": "Sample Survey 2",
                "description": "Report description goes here",
                "creation_date": "March 21, 2016",
                "date_range": "03/01/2016-05/15/2016",
                "data_sets": "Facility A, Nursing Department"
            }
        },
        {
            "id": 1,
            "type": "archive",
            "attributes": {
                "name": "Sample Survey 3",
                "description": "Report description goes here",
                "creation_date": "March 21, 2015",
                "date_range": "03/01/2015-05/15/2015",
                "data_sets": "Facility A, Nursing Department"
            }
        }
    ]
};

export default archives;

上面的代码拥有我正在使用的真实模拟数据。

然后从中提取年份。因为我希望能够遍历这些年并将它们放在一个列表中

<ul>
  <li>2018</li>
  <li>2017</li>
  <li>2016</li>
  <li>2015</li>
  <li>2014</li>
  <li>2013</li>
  <li>2012</li>
</ul>

【问题讨论】:

  • 请发布您的代码。
  • 第 3 行的附加 f 是错字吗?
  • 有时候会很无聊……例如就像这里一样,所有答案都被否决了,没有真正的解释。这与 SO 的否决权有何关系,他说:“应为极端情况保留否决权。它不能代替沟通和编辑。与其否决票:如果有问题,请留下一个评论或编辑帖子以更正它。”
  • @Bucket 我发布了我正在使用的实际模拟数据。

标签: javascript html json regex


【解决方案1】:
var str = [
  "March 21, 2018",
  "March 21, 2017f",
  "March 21, 2016",
  "March 21, 2015",
  "March 21, 2014",
  "March 21, 2013",
  "March 21, 2012"
]; 

//Array to hold the years
let years = [];

//Iterate your date collection
for(let i = 0; i < str.length; i++){
    //Split the string on the comma
    const splitter = str[i].split(",");

    //If the split produces more than one string value, meaning we have a formatted date
    if(splitter.length > 1){
       //Replace any non digit characters and trim whitespace
       let year = splitter[1].replace(/\D/g,'').trim();
       //push year value into new array
       years.push(year);

    }
}

//View the results in console
console.log(years);

【讨论】:

    【解决方案2】:

    如果您的字符串始终采用相同的格式,您可以在 , 上进行拆分。我使用正则表达式/[^0-9]/gi 将年份中不是数字的任何内容替换为非字符''。这可以防止像 2017f 这样的东西包含 f.

    var dates = [
      "March 21, 2018",
      "March 21, 2017f",
      "March 21, 2016",
      "March 21, 2015",
      "March 21, 2014",
      "March 21, 2013",
      "March 21, 2012"
    ]; 
    
    const years = [];
    for(const date of dates){
      const year = date.split(',')[1].replace(/[^0-9]/gi, '').trim();
      years.push(year);
    }
    
    console.log(years);

    【讨论】:

      【解决方案3】:

      至少匹配四位数字,至少对于您的情况

      (str =&gt; str.match(/\d{4}/)[0])

      var dateStrings = [
        "March 21, 2018",
        "March 21, 2017f",
        "March 21, 2016",
        "March 21, 2015",
        "March 21, 2014",
        "March 21, 2013",
        "March 21, 2012"
      ];
      var years = dateStrings.map(str => str.match(/\d{4}/)[0]);
      var ul = years.reduce((ul, year) => {
        var li = document.createElement('li');
        li.innerHTML = year;
        ul.appendChild(li);
        return ul;
      }, document.createElement('ul'));
      
      document.body.appendChild(ul);

      【讨论】:

      • 是的,几乎一样
      • 比其他人建议的要容易得多
      • @JuanMendes 那么,做 2 个循环,一个 map 然后一个 forEach 怎么这么容易呢? ...在我的情况下,我只使用一个循环,效率更高。
      • @LGSon 要点是正则表达式,4 位数字真的很容易阅读,并且不需要您匹配两件事(假设更多关于输入)。这与效率无关,而是看代码的难易程度。我在这里没有看到任何性能瓶颈,我认为函数式编程的优雅不会让您付出任何明显的代价。但同样,这不是问题的重点。 “尝试在 javascript 中匹配字符串中的年份”
      • @JuanMendes 鉴于这里的用户将接受一个答案赞成/工作的代码,并在他们自己的代码中使用它,这可能很重要,做 2 个循环,那么为什么要奖励它呢?跨度>
      【解决方案4】:

      使用匹配项并检查 4 位数字:/\d{4}/

      var str = [
        "March 21, 2018",
        "March 21, 2017f",
        "March 21, 2016",
        "March 21, 2015",
        "March 21, 2014",
        "March 21, 2013",
        "March 21, 2012"
      ];
      
      let ul = document.querySelector('ul')
      
      str.forEach(date => {
        let matches = date.match(/\d{4}/)
        matches.length > 0 ? (ul.innerHTML += `<li>${matches[0]}</li>`) : null
      })
      &lt;ul&gt;&lt;/ul&gt;

      【讨论】:

      【解决方案5】:

      试试这个:

      var archives = {
          "data": [{
                  "id": 1,
                  "type": "archive",
                  "attributes": {
                      "name": "Employee Engagement Summary",
                      "description": "Report description goes here",
                      "creation_date": "March 21, 2018",
                      "date_range": "03/01/2018-05/15/2018",
                      "data_sets": "Facility A, Nursing Department"
                  }
              },
              {
                  "id": 1,
                  "type": "archive",
                  "attributes": {
                      "name": "Sample Survey 1",
                      "description": "Report description goes here",
                      "creation_date": "March 21, 2017",
                      "date_range": "03/01/2017-05/15/2017",
                      "data_sets": "Facility A, Nursing Department"
                  }
              },
              {
                  "id": 1,
                  "type": "archive",
                  "attributes": {
                      "name": "Sample Survey 2",
                      "description": "Report description goes here",
                      "creation_date": "March 21, 2016",
                      "date_range": "03/01/2016-05/15/2016",
                      "data_sets": "Facility A, Nursing Department"
                  }
              },
              {
                  "id": 1,
                  "type": "archive",
                  "attributes": {
                      "name": "Sample Survey 3",
                      "description": "Report description goes here",
                      "creation_date": "March 21, 2015",
                      "date_range": "03/01/2015-05/15/2015",
                      "data_sets": "Facility A, Nursing Department"
                  }
              }
          ]
      };
      
      var yearsRange = archives.data.map(obj => obj.attributes.date_range);
      
      var yearArr= [];
      
      yearsRange.filter(item => {
         yearArr.push(item.split('/')[2].split('-')[0]);
      });
      
      console.log("yearArr", yearArr);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-24
        • 2016-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多