How to do date masking using javascript (without JQuery)?

后端 未结 4 619
太阳男子
太阳男子 2020-12-09 00:26


        
4条回答
  •  情书的邮戳
    2020-12-09 01:14

    I had some trouble getting the currently accepted answers to work properly while retaining the ability to backspace. This was my solution. It retains backspacing and also doesn't show the slash until the number following it is typed.

    const maskDate = value => {
      let v = value.replace(/\D/g,'').slice(0, 10);
      if (v.length >= 5) {
        return `${v.slice(0,2)}/${v.slice(2,4)}/${v.slice(4)}`;
      }
      else if (v.length >= 3) {
        return `${v.slice(0,2)}/${v.slice(2)}`;
      }
      return v
    }
    

    I've also create a github gist for this snippet here.

提交回复
热议问题