0

In Typescript, I'm trying to parse a string provided, in the form "DD/MM/YYYY"; the string can have one or two digits for day and month; for example:
8/10/2019 or 08/10/2019; 10/8/2019 or 10/08/2019.
I'have tried the following code, but ddDate is always null.

const regExp = new RegExp("^d{1,2}/d{1,2}/d{4}$");
const ddDate = dd.match(regExp)!;
user1
  • 556
  • 2
  • 6
  • 22
  • And you haven't found a possible solution here on SO? – Andreas Oct 08 '19 at 09:36
  • I've searched on SO, and I think my solution is right; however it does not work, so I asked because clearly there is something I don't know about regular expression and / or match function. – user1 Oct 08 '19 at 09:41
  • Possible duplicate of [Javascript date regex DD/MM/YYYY](https://stackoverflow.com/questions/5465375/javascript-date-regex-dd-mm-yyyy) – Andreas Oct 08 '19 at 09:44

1 Answers1

3

What you wrote:

^d{1,2}/d{1,2}/d{4}$

  • / needs to be escaped with \, i.e. \/
  • d is going to match the string literal d. You probably wanted \d to match any number.

So, what you actually want:

^\d{1,2}\/\d{1,2}\/\d{4}$

const regExp = /^\d{1,2}\/\d{1,2}\/\d{4}$/; // or new RegExp("^\d{1,2}\/\d{1,2}\/\d{4}$");

console.log("12/12/2019".match(regExp)); // yes
console.log("2019/12/12".match(regExp)); // no
console.log("12/2019/12".match(regExp)); // no

I recommend testing this sort of thing at regex101

ed'
  • 1,815
  • 16
  • 30