gpt4 book ai didi

JavaScript:正则表达式将此 "2018Jun12-2018Jul11"日期字符串替换为此 "Jun 12, 2018 - Jul 11, 2018"日期字符串

转载 作者:行者123 更新时间:2023-12-02 21:52:52 25 4
gpt4 key购买 nike

如果我有以下字符串:

var str = "2018Jun12-2018Jul11";

是否有一个正则表达式可以将其转换为:"Jun 12, 2018 - Jul 11, 2018"str.replace()

最佳答案

尽管这涉及通过“替换器”回调进行一些字符串格式化逻辑,但一种基于 String#replace() 的解决方案将是:

const input = `2018Jun12-2018Jul11`;
const output = input.replace(
/* Search for matches of this pattern, and extract groups */
/(\d+)([a-z]+)(\d+)/gi,
/* Replacer function formats the extracted values as required */
(_,year,month,date) => `${month} ${date}, ${year}`
)
/* If you need white space around the hyphen */
.split('-').join(' - ')

console.log(input, ' -> ', output)

这里的想法是匹配任何出现的模式“年份数字(\d+),月份字符串[a-z]+,日期数字(\d+ )"在您的输入字符串中。在模式中使用 ( ) 会导致从模式匹配中提取相应的值。 Replacer 回调返回一个字符串,该字符串将这些提取的值重新排列为所需的格式。该字符串将成为输出中匹配项的替换值。

希望有帮助

关于JavaScript:正则表达式将此 "2018Jun12-2018Jul11"日期字符串替换为此 "Jun 12, 2018 - Jul 11, 2018"日期字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60085674/

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