js处理字符串时间的方法

  const parseTimeString = (timeString) => {
  if (/^\d+$/.test(timeString)) {
    return `${timeString}个月`; // 纯数字自动加上月单位
  }
  const monthMatch = timeString.match(/(\d+)个月/);
  const dayMatch = timeString.match(/(\d+)天/);
  const months = monthMatch ? `${monthMatch[1]}个月` : '';
  const days = dayMatch ? `${dayMatch[1]}天` : '';
  // 如果只有天数或者只有月数,直接返回
  if (months && !days) return months;
  if (days && !months) return days;
  // 如果有月数也有天数,返回组合的字符串
  return `${months}${days}`;
};

时间字符串可能是“1天”

时间字符串可能是“39个月”

时间字符串可能是“39个月1天”

时间字符串可能是“39”

这个方法可以根据4种字符串都把数字截取出来根据天跟日4种其他再return返回回去想要的格式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值