简体   繁体   English

如何在Javascript中反转字符串插值

[英]How do you reverse String Interpolation in Javascript

OK lets say I have a string that changes everyday that contains the date in it 好的,可以说我有一个每天都会更改的字符串,其中包含日期

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

how do I extract the date out of it to example formatreceiveddate = "2018-07-14" 我如何将日期提取到示例formatreceiveddate = "2018-07-14"

I know the other way around is to use string interpolation and template literals but not how to reverse it 我知道另一种方法是使用字符串插值和模板文字,而不是如何反转它

So what I really is asking how to transform this 所以我真正在问如何改变这个

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 

into this 2018-07-14 for each date. 每个日期进入此2018-07-14

There may be a more elegant way than this, but this is the first thing that came to mind. 可能有比这更优雅的方法,但这是我想到的第一件事。 Split the string up and make a date object with it. 拆分字符串,并使用它创建一个日期对象。

 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); 

The 'string approach' with a regex is is perhaps naive compared to using actual Date objects, but it's pretty simple: 与使用实际的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); } 

If you're okay with using a third-party library, moment makes this incredibly simple: 如果您可以使用第三方库,那么此刻将使操作变得异常简单:

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"

As per the documentation, the moment constructor takes the input date as the first argument, and an optional format string as the second argument. 根据文档, moment构造函数将输入日期作为第一个参数,并将可选的格式字符串作为第二个参数。 A quick breakdown of the format string: 格式字符串的快速细分:

  • the square brackets denote escaped text 方括号表示转义文字
  • dddd full day of the week text dddd一周中的整天文本
  • Do day of the month, with postfix modifier (st, th, etc.) Do这个月的一天,后缀修饰符(ST,日等)
  • MMMM full month text MMMM整月文字
  • YYYY 4 digit year YYYY 4位数字的年份

Output format follows the same rules, which can be found here . 输出格式遵循相同的规则,可在此处找到。 I would only recommend this approach compared to the other answers here if you plan on doing additional time computations. 如果您打算进行更多的时间计算,那么与这里的其他答案相比,我只会推荐这种方法。 Otherwise, importing a library is likely overkill! 否则,导入库可能会过大!

You can look for the date pattern, get the the values and use them to create a date. 您可以查找日期模式,获取值,然后使用它们创建日期。 It's good to make the parse as least reliant on the overall string as you can so that changes are tolerated to some extent. 最好使解析尽可能不依赖整个字符串,以便可以在一定程度上容忍更改。

The following just looks for the date part at the end of the string (eg 14th of July 2018), it doesn't matter what the first part is. 下面只是在字符串末尾查找日期部分(例如,2018年7月14日),第一部分是什么都没有关系。 It will even tolerate a string that is just a date like "14 July 2018". 它甚至可以容忍像“ 2018年7月14日”之类的日期的字符串。 Eg 例如

 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*) ([az]+) (\\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()); }); 

There's a bit of error handling incase match doesn't find a match and returns null . 如果match找不到匹配项并返回null,则存在一些错误处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM