javascript - 使用正则表达式从日期产生年份和月份
问题描述
我正在尝试使用正则表达式以 yyyy-MM 格式提取日期。
我拥有的数据可能是:
2019年9月予定 --> Should yield 201909
2020年5月 --> Should yield 202005
2019年8月下旬 --> Should yield 201908
到目前为止,我发现的唯一方法是在几个正则表达式中提取它:
(?<!年)(\d) --> Working but not nice
(?<!月)(\d) --> Not working as also selecting the year
解决方案
您可以执行以下操作(假设月后没有更多数字)
function extractDate(text) {
const matches = text.match(/\d+/g);
return matches.join(matches[1].length === 1 ? '0' : '');
}
console.log(extractDate('2019年8月下旬')) //should return 201908
console.log(extractDate('2019年12月下旬')) //should return 201912
推荐阅读
- javascript - 到达目标部分时淡出 vue.js 中的 Div / Section
- javascript - JavaScript 待机功能是否存储在 RAM 或硬盘中?
- graphql - 如何定义特定于 GraphQL 中两个节点的连接的值?
- javascript - Bokeh 中的自定义 javascript 回调以从数据框中选择列并更新绘图
- javascript - ReactJS - Array.map 和键的行为不明确
- python - SQLAlchemy - 如何创建没有项目的一对多关系?
- angular - Angular,有没有办法“markAsTouched”没有表单的字段?
- python - Python3.7 venv 不创建虚拟环境目录
- linux - 对“_gfortran_transfer_character_write”的未定义引用
- vba - Excel 复制到多个工作表