user1
user1

Reputation: 586

Regular expression on date in Typescript

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)!;

Upvotes: 0

Views: 636

Answers (1)

ed'
ed'

Reputation: 1895

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

Upvotes: 3

Related Questions