gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:30:03 30 4
gpt4 key购买 nike

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

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com