【问题标题】:How do you reverse String Interpolation in Javascript你如何在Javascript中反转字符串插值
【发布时间】:2018-07-15 04:52:28
【问题描述】:

好吧,假设我有一个每天都在变化的字符串,其中包含日期

var receiveddate = "Received on Saturday 14th of July 2018"

如何从中提取日期到示例formatreceiveddate = "2018-07-14"

我知道另一种方法是使用字符串插值和模板文字,但不知道如何反转它

所以我真正要问的是如何改变这个

Received on Saturday 14th of July 2018
Received on Saturday 5th of May 2018
Received on Monday 8th of January 2018
Received on Wednesday 19th of July 2017
Received on Sunday 1st of July 2018
Received on Tuesday 3rd of July 2018
Received on Saturday 2nd of June 2018
Received on Thursday 21st of June 2018
Received on Thursday 31st of May 2018 

每个日期进入这个2018-07-14

【问题讨论】:

    标签: javascript date


    【解决方案1】:

    可能有比这更优雅的方式,但这是首先想到的。拆分字符串并用它创建一个日期对象。

    const dateString = "Received on Saturday 14th of July 2018";
    
    // Split the string up by spaces
    const dateParts = dateString.split(' ');
    
    // Grab each part of the date. We parse the day as an int to just get the numeral value
    const month = dateParts[5];
    const day = parseInt(dateParts[3]);
    const year = dateParts[6];
    
    // Parse the date by reassembling the string
    const date = new Date(month + ' ' + day + ' ' + year);
    
    // Output in your desired format (ISO)
    const formattedDate = date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();
    
    console.log(formattedDate);

    【讨论】:

    • 如果您需要该月的前导 0,请参阅 stackoverflow.com/questions/25159330/…
    • 这个有效,是的,在您提供的链接中的前导 0 的帮助下,我也不需要最后一部分,因为 const date = new Date(month + ' ' + day + ' ' +年);已经以我需要的格式给了我日期我只需要使用 formattedDate = date.toISOString().substring(0, 10);而不是 const formattedDate = date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();删除时间和秒,它有前导 0
    • 这是绝对错误的,不能保证产生正确的结果。使用更长的日期构造函数 (new Date(year, month, day)。
    【解决方案2】:

    如果您可以使用第三方库,moment 让这变得非常简单:

    let dtStr = moment(
       "Received on Saturday 14th of July 2018",
       "[Received on] dddd Do [of] MMMM YYYY"
    ).format("YYYY-MM-DD");
    // dtStr = "2018-07-14"
    

    根据文档,moment 构造函数将输入日期作为第一个参数,将可选格式字符串作为第二个参数。格式字符串的快速分解:

    • 方括号表示转义文本
    • dddd一周中的全天文本
    • Do 月份中的某一天,带有后缀修饰符(st、th 等)
    • MMMM满月文
    • YYYY 4 位数年份

    输出格式遵循相同的规则,可以找到here。如果您计划进行额外的时间计算,与此处的其他答案相比,我只会推荐这种方法。否则,导入库很可能是矫枉过正!

    【讨论】:

      【解决方案3】:

      您可以查找日期模式、获取值并使用它们来创建日期。最好使解析尽可能少地依赖整个字符串,以便在一定程度上容忍更改。

      以下内容仅查找字符串末尾的日期部分(例如 2018 年 7 月 14 日),第一部分是什么并不重要。它甚至可以容忍像“2018 年 7 月 14 日”这样的日期字符串。 例如

      function parseString(s) {
        var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' '),
            parts  = s.match(/(\d+)(st|rd|th)?( ?\w*) ([a-z]+) (\d{4})$/i) || [],
            day    = parts[1],
            month  = (parts[4] || '').toLowerCase().slice(0,3),
            year   = parts[5];
      
        return new Date(year, months.indexOf(month), day);
      }
      
      [ 'Received on Saturday 14th of July 2018',
        'Received on Saturday 5th of May 2018',
        'Received on Monday 8th of January 2018',
        'anything you like, even War and Peace 19th July 2017',
        '31 December 2012',
        'Totally invalid string'
      ].forEach(s => {
        var d = parseString(s);
        console.log(isNaN(d)? d : d.toString());
      });

      如果 match 没有找到匹配项并返回 null,则会进行一些错误处理。

      【讨论】:

      • 反对的选民愿意解释他们的投票吗?然后我可以考虑批评并希望改进未来的答案。
      【解决方案4】:

      与使用实际的 Date 对象相比,带有正则表达式的“字符串方法”可能是幼稚的,但它非常简单:

      var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
      var regex = /received on \w+ (\d+).*?of (\w+) (\w+)/ig;
          var result;
          while (result = regex.exec(input)) {
            var month = months.indexOf(result[2]) + 1;
            console.log(result[3] + "-" + month + "-" + result[1]);
          }
      

      //with zero-padding
      var input = `Received on Saturday 14th of July 2018
      Received on Saturday 5th of May 2018
      Received on Monday 8th of January 2018
      Received on Wednesday 19th of July 2017
      Received on Sunday 1st of July 2018
      Received on Tuesday 3rd of July 2018
      Received on Saturday 2nd of June 2018
      Received on Thursday 21st of June 2018
      Received on Thursday 31st of December 2018`
      
      var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
      var regex = /received on \w+ (\d+).*?of (\w+) (\w+)/ig;
      var result;
      while (result = regex.exec(input)) {
        var month = months.indexOf(result[2]) + 1;
        month = /\d{2,}/.test(month) ? month : "0" + month;
        var day = result[1];
        day = /\d{2,}/.test(day) ? day : "0" + day;
        console.log(result[3] + "-" + month + "-" + day);
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-05
        • 2021-09-28
        相关资源
        最近更新 更多