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

标签 javascript date

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

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

最佳答案

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

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

关于javascript - 你如何在 Javascript 中反转字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51345374/

相关文章:

javascript - 在wordpress中x秒后隐藏div

javascript - 嵌入在其他网站上的 JS - 如何在不搞砸其他 jQuery 安装的情况下使用 jQuery?

excel - VLOOKUP 返回空白为 1/0/1990,而不是没有任何可见的内容

excel - VBA日期+逻辑

Javascript:在插入 Google 表格之前按月而不是按天对 csv 数据进行分组

javascript - 循环遍历对象和未知数量的子对象

javascript - 将表单提交到新窗口/标签

javascript - 原型(prototype)和关闭

javascript date.utc问题

java - 在 Java8 Date API 中将持续时间转换为年?