Here are a couple of issues to address:
You need to consider that your backslashes are within a string literal.
You're failing to provide any input to the compile
function.
1. Understanding Backslashes
Keep in mind that in a string literal, a backslash serves as an escape character. This means that \d
in your string actually escapes the letter d
, resulting in just d
. Hence, your actual regular expression should be:
^(d{1,2}/d{1,2}/d{1,2})
It's better to use the literal form like this:
const reg: RegExp = /^(\d{1,2}\/\d{1,2}\/\d{1,2})/; // No `compile`, see next point
Check out this live example:
const stringWithDate/*: string*/ = "4/7/20 This is a date!";
const reg/*: RegExp*/ = /^(\d{1,2}\/\d{1,2}\/\d{1,2})/; // No `compile`, see next point
const exist/*: boolean*/ = reg.test(stringWithDate)
const matches/*: RegExpExecArray | null*/ = reg.exec(stringWithDate);
console.log(exist);
console.log(matches);
2. The compile
Function
The compile
function requires a new expression to compile, replacing the existing one. Not providing an expression will result in the default blank match at the start of your string represented by (?:)
.
Omit compile
(spec | MDN). It's an Annex B feature primarily for JavaScript engines in web browsers. As per the spec note:
The compile
method completely reinitializes the this object RegExp with a new pattern and flags. An implementation may interpret use of this method as an assertion that the resulting RegExp object will be used multiple times and hence is a candidate for extra optimization.
However, JavaScript engines can optimize regex patterns without explicit instructions.
If you decide to utilize compile
, here's how:
const reg: RegExp = /x/.compile(/^(\d{1,2}\/\d{1,2}\/\d{1,2})/);
This action will fully replace the original regular expression with the provided pattern and flags when invoking compile
.
Note: Avoid unnecessary type annotations on those const
s. TypeScript inherently infers types accurately.