Search code examples
javascriptregexone-time-password

Regex to match exactly 6 digits with any number of spaces between the digits


I recently needed to create a regular expression for OTP values in JavaScript. The input should contain 6 digits with spaces any where in between. I am not regex-savvy at all and even though I tried looking for a better way, I ended up with this:

/^[\d ]*$/

With this I can have spaces with digits but here I don't have control over the number of digits.


Solution

  • Try this:

    let OTPs = [
      "123456", 
      "12345", // Invalid
      "1 2345 6", 
      "1 2 3 4 5 6", 
      "1 2 3 4    5 6",
      "a 2 b 4 5 6" // Invalid
    ]
    
    let validOTPs = OTPs.filter(otp => otp.match(/^(\d\s*){6}$/g))
         
    console.log(validOTPs)