Having trouble extracting a list of matches using a Regular Expression?

const stringWithDate: string = "4/7/20 This is a date!";
const reg: RegExp = new RegExp("^(\d{1,2}\/\d{1,2}\/\d{1,2})").compile();
const exist: boolean = reg.test(stringWithDate)
const matches: RegExpExecArray | null = reg.exec(stringWithDate);
console.log(exist);
console.log(matches);

I have been attempting to extract the date (4/7/20) from stringWithDate. Despite 'exist' showing true when logged, the matches array displays [""] instead of the expected result. I am perplexed by this issue as my regex expression, while not perfect, has worked in both Python and on regexr.com. It seems like it should return "4/7/20" from stringWithDate, but for some reason, that is not the case.

Answer №1

Here are a couple of issues to address:

  1. You need to consider that your backslashes are within a string literal.

  2. 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 consts. TypeScript inherently infers types accurately.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues have arisen with compiling TypeScript due to the absence of the 'tsc command not found' error

Attempting to set up TypeScript, I ran the command: npm install -g typescript After running tsc --version, it returned 'tsc command not found'. Despite trying various solutions from Stack Overflow, GitHub, and other sources, I am unable to reso ...

Troubleshooting an issue with a Typescript React component that is generating an error when using

I am in the process of implementing unit testing in a Typescript and React application. To start off, I have created a very basic component for simplicity's sake. import React from "react"; import ReactDOM from "react-dom"; type T ...

Step-by-step guide to creating a custom wrapper in React that modifies the props for a component

Exploring React components for the first time and seeking assistance. I am interested in dynamically wrapping one component inside another and modifying its props. For instance, considering the following component: If we want to pass the key3 from a wrapp ...

Nestjs: Can't find property in Mongoose document

I am currently encountering some issues with the following code while using Nestjs along with Mongoose: import { Injectable } from '@nestjs/common'; import { Key, KeyDocument } from '@app/mongo'; import { Model } from 'mongoose&apo ...

What is the proper way to utilize setTimeout in TypeScript?

Let's take a look at an example of how to use setTimeout in Angular and TypeScript: let timer: number = setTimeout(() => { }, 2000); However, upon compilation, you may encounter the following error message: Error TS2322: Type 'Timeout' ...

Incorporate keyboard input functionality into an object wrapper

Adding typing to a class that encapsulates objects and arrays has been a bit tricky. Typing was easily implemented for objects, but ran into issues with arrays. interface IObject1 { value1: string, } interface IObject2 { myObject: IObject1, ...

Ways to resolve the issue of npm being unable to globally install typescript

While trying to globally install TypeScript using npm sudo npm install -g typescript An error occurs during the installation process with the following message: ENOENT: no such file or directory, chmod '/usr/local/lib/node_modules/typescript/bin/ ...

The type '{} is not compatible with the type 'IProps'

In my current project, I am utilizing React alongside Formik and TypeScript. The code snippet below demonstrates my usage of the withFormik Higher Order Component (HOC) in my forms: import React from 'react'; // Libraries import........ import { ...

Ways to implement es6 in TypeScript alongside react, webpack, and babel

Being new to front-end development, I have found that following a simple tutorial can quickly help me start tackling problems in this field. One issue I've encountered is with ES5, which lacks some of the tools that are important to me, like key-value ...

What is the proper way to enhance properties?

In the process of developing a Vue3 app using Typescript, one of the components is designed to receive data through props. Initially, everything functioned smoothly with the basic setup: props: { when: String, data: Object }, However, I de ...

Could one retrieve the value of a type and save it as a constant?

Can I achieve something similar to this: type YesType = true; const myVar = GetTypeValue<YesType>(); // In this instance, the value true is assigned Is it feasible to assign other fixed values to constant variables like in C++? ...

Formatting the string value

Having trouble formatting the input value. Take a look at this code snippet: <input type="text" class="form-control" name="time" formControlName="time" (input)="convertToMinute($event.target.value)" /> Here is the function in question: ...

Tips for troubleshooting TypeScript Express application in Visual Studio Code

Recently, I attempted to troubleshoot the TypeScript Express App located at https://github.com/schul-cloud/node-notification-service/ using Visual Studio Code. Within the launch.json file, I included the following configuration: { "name": "notifi ...

Getter and Setter Implementation in Typescript without Using Classes

Check out these various SO questions discussing Typescript getters/setters: from 2015, Jan 2018, Sept 2018, and more. Now, the question arises - what is the best approach to define Typescript types for getters/setters in a plain JavaScript object without ...

Creating mock objects with Jest

I am currently delving into the world of jest testing. Here is a snippet from an implementation class I'm working with: import { ExternalObject } from 'external-library'; export class MyClass { public createInstance(settings : ISettings) ...

Unexpected behavior observed with negated character: ? ^

I am looking to create a form where users can input their phone number and have the flexibility to choose how they want to separate the numbers. I have been using a regex pattern for validation: var regex = /[^0-9 \/-\\\(\)\+ ...

Looking to troubleshoot an error in my TypeScript reducer implementation. How can I fix this issue?

I'm currently using typescript along with react, redux, and typessafe-actions. However, I've come across a particular error that I need help with. The error message reads: "No overload matches this call. Overload 1 of 2, '(...items: Concat ...

Avoiding the use of reserved keywords as variable names in a model

I have been searching everywhere and can't find a solution to my unique issue. I am hoping someone can help me out as it would save me a lot of time and effort. The problem is that I need to use the variable name "new" in my Typescript class construct ...

JavaScript alert box

I'm fairly new to the world of web development, with knowledge in CSS & HTML and currently learning TypeScript. I'm attempting to create a message icon that opens and closes a notifications bar. Here's where I'm at so far: document.getE ...

What methods are available to prevent redundant types in Typescript?

Consider an enum scenario: enum AlertAction { RESET = "RESET", RESEND = "RESEND", EXPIRE = "EXPIRE", } We aim to generate various actions, illustrated below: type Action<T> = { type: T; payload: string; }; ty ...