-5

I would like to implement regex in Javascript to compare if my string matches the following pattern -

<digit><digit>/<digit><digit>/<digit><digit><digit><digit>

This is similar to the DD/MM/YYYY format. But I don't want any date specific validations. I just want to check if the string contains digits as per the given pattern.

Thanks!

Archit Arora
  • 2,508
  • 7
  • 43
  • 69

2 Answers2

0

Something like that?

re = new RegExp(/\d{2}\/\d{2}\/\d{4}/);

"21/02/2017".match(re) /* ["21/02/2018", index: 0, input: "21/02/2018"] */
"21/2/2017".match(re)  /* null */
Alexei Danchenkov
  • 2,011
  • 5
  • 34
  • 49
0

Alexei Danchenkov makes good answer, but maybe you also want additional checks for start and the end of the string:

re = new RegExp(/^\d{2}\/\d{2}\/\d{4}$/);

// examples
console.log("21/02/2017".match(re)); /* ["21/02/2018", index: 0, input: "21/02/2018"] */
console.log("21/2/2017".match(re));  /* null */
console.log("21/02/20171".match(re)); /* null */
console.log("21/02/2017 ".match(re)); /* null */
console.log("+21/02/2017".match(re)); /* null */
A. Denis
  • 562
  • 7
  • 15