RegExp.$1~9被弃用后替换方法

发布时间 2023-04-24 11:23:47作者: 小小菜鸟04
RegExp.$1使用
function formatFunction(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substring(4 - RegExp.$1.length)
    );
  }
  const o = {
    "M+": date.getMonth() + 1, // 月份
    "d+": date.getDate(), // 日
    "h+": date.getHours(), // 小时
    "m+": date.getMinutes(), // 分
    "s+": date.getSeconds(), // 秒
    "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  };
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1
          ? o[k]
          : ("00" + o[k]).substring(("" + o[k]).length)
      );
    }
  }
  return fmt;
};
 
替换方法: RegExp的exec方法
    function formatFunction(date, fmt) {
        const re = /(y+)/;
        if (re.test(fmt)) {
            const t = re.exec(fmt)[1];
            fmt = fmt.replace(
                t,
                (date.getFullYear() + "").substring(4 - t.length)
            );
        }

        const o = {
            "M+": date.getMonth() + 1, // 月份
            "d+": date.getDate(), // 日
            "h+": date.getHours(), // 小时
            "m+": date.getMinutes(), // 分
            "s+": date.getSeconds(), // 秒
            "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
            S: date.getMilliseconds(), // 毫秒
        };
        for (let k in o) {
            const regx = new RegExp("(" + k + ")");
            if (regx.test(fmt)) {
                const t = regx.exec(fmt)[1];
                fmt = fmt.replace(
                    t,
                    t.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
                );
            }
        }
        return fmt;
    };
 
----------------------------使用-----------
    function btn() {
        const t = this.formatFunction(new Date(), "yyyy-MM-dd hh:mm:ss");
        console.log(t);
    };
输出:2023-04-24 11:14:15