[英]How to remove '-' from a date if it is the last character?
我有一个 function 接收来自用户的 3 个输入:年、月和日。
如果已设置年份,用户只能设置月份。 如果设置了月份,也只能设置日期。
最后,object 看起来像这样:
updatedFields.push({
id: book.id,
readIn: `${year}-${month}-${day}`,
});
问题是用户没有义务告知任何事情。 因此,如果它只通知年份和月份或年份,我会有类似的东西:
"2020--" // if he only enters the year
"2021-10-" // if he enters the year and month
"2022-03-13" // if it enters year, month and day
问题是:如何删除多余-
破折号?
从可能的值构造一个数组,过滤掉那些不存在的,然后用分隔符连接它。
readIn: [year, month, day].filter(Boolean).join('-')
您可以使用正则表达式来删除尾随字符。
updatedFields.push({
id: book.id,
readIn: `${year}-${month}-${day}`.replace(/-+$/, '')
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.