1

I am trying to put below regular expression in Angular6:

const regexp = new RegExp('^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$');

But as it is implied, it is throwing

Module parse failed: Octal literal in strict mode 

By the fact I understand I can use \\ instead of \ to avoid this. But is there any improvised way to get it done in Typescript.

Please suggest a solution.

jaykhatri
  • 123
  • 1
  • 10
  • Start by using a regular expression literal rather than the constructor. (Avoid using the constructor except when you need to dynamically create the pattern from a variable) – CertainPerformance Dec 29 '18 at 01:27
  • Great! Can you create an answer with example. So that I may mark it and may help visitors – jaykhatri Dec 29 '18 at 01:30
  • Possible duplicate of [Why do regex constructors need to be double escaped?](https://stackoverflow.com/questions/17863066/why-do-regex-constructors-need-to-be-double-escaped) – CertainPerformance Dec 29 '18 at 01:48
  • @CertainPerformance I changed question title. Is it fine now. – jaykhatri Dec 29 '18 at 01:55

1 Answers1

0

Using .test statement for regular express have helped me, below is the working code of the same:

if (/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/.test(record['dateofbirth'])) {
            this.validated = false;
            this.validatedtext = this.validatedtext + '\n Date of Birth for record no. ' + i + ' is not correctly formatted';
          }

and this link have helped me out:

https://toddmotto.com/understanding-regular-expression-matching-with-test-match-exec-search-and-split/

jaykhatri
  • 123
  • 1
  • 10