Finding the number enclosed within two characters - TypeScript

Recently, I've started exploring Typescript and I'm currently working on creating a webhook within my Google Cloud Functions.

In one of the scenarios, I have this string:

C1234567890A460450P10TS1596575969702

My objective is to utilize regex to isolate the number 1234567890 from the given string. Please note that the first character C remains constant, while the succeeding character A can vary and be any other alphabet.

The regex pattern that effectively captures the desired number is: (?<=C)(\d{10})(?=\w).

If someone could guide me on how to implement this regex in Typescript so that I can store the extracted number in a variable (for example:

const number = [the number extracted from the string] //value 1234567890
)

Edit 1:

After attempting the suggestions provided by others (which I had already experimented with before asking this question), I was able to come up with the following code snippet:

const string = request.body.string;

let regxp = new RegExp('(?<=C)(\d{10})(?=\w)');
const number = regxp.exec(string);

response.send(number);

However, executing this code resulted in an empty response.

Answer №1

Two main issues need to be addressed here. First, you forgot to convert the returned string into a number using parseInt. Additionally, remember that (?<=C) (positive lookbehind) may not always be supported.

Another improvement could be simplifying your regular expression to ^C\d{10} and utilizing .splice(1) to eliminate the initial C.

const inputString: string = request.body.string;

const matches = inputString.match(/^C\d{10});
let finalNumber: number;
if(matches !== null) {
    finalNumber = parseInt(matches[0].slice(1));
} else {
    res.status(400).end(); // If using Express
    return;
}

res.send(finalNumber); // Should output 1234567890

Try it out on TypeScript Playground

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

Is it possible for Go's http server to compile TypeScript?

My current setup involves a NodeJS Application that launches an http server and utilizes client side code written in TypeScript with Angular 2. I'm curious if it's possible to achieve the same functionality using Go programming language? I trie ...

Simulated database in a Service using TypeScript with Node

Struggling with a unit test, I need to mock the this.orderRepository.findById(id); method to find an object by its ID. Although I've set the return value, the test keeps failing. This is my first time creating a unit test in Node using TypeScript and ...

Tracking user session duration on a React Native app can be achieved by implementing a feature that monitors and

I'm currently focusing on tracking the amount of time a user spends on the app in minutes and hours, and displaying this information. I have successfully implemented the functionality to count minutes, but I am struggling to figure out how to track wh ...

In Typescript, a function that is declared with a type other than 'void' or 'any' is required to have a return value

I'm a beginner in Angular2/Typescript and I am encountering an error while trying to compile my project: An error is showing: A function that has a declared type other than 'void' or 'any' must return a value. Here is the code sn ...

What is the best way to implement filter functionality for individual columns in an Angular material table using ngFor?

I am using ngFor to populate my column names and corresponding data in Angular. How can I implement a separate filter row for each column in an Angular Material table? This filter row should appear below the header row, which displays the different column ...

"What could be causing my React application to enter a never-ending re-rendering cycle when I incorporate

Currently, I'm working on a code to update the content of a previous post with image URLs received from the server. However, I'm facing issues with excessive re-renders due to my coding approach. Specifically, when converting the image URLs into ...

How to Use Regex to Capture the Initial Portion of a Text

I have a list of phrases that need to be cleaned up: [ 'This is erleada comp. recub. con película 60 mg.', 'This is auxina e-200 uicaps. blanda 200 mg.', 'This is ephynalsol. iny. 100 mg.', 'This is paracethamol ...

Regular expression: Rearrange the order of matches within a capturing group

To successfully extract user identities from a smartcard, I must adhere to the pattern format: CN=LAST.FIRST.MIDDLE.0000000000 The desired result should be: FIRST.LAST If this process were implemented in my own code, it would be straightforward: # Sampl ...

I'm wondering why Jest is taking 10 seconds to run just two simple TypeScript tests. How can I figure out the cause of this sluggish performance?

I've been experimenting with Jest to execute some TypeScript tests, but I've noticed that it's running quite slow. It takes around 10 seconds to complete the following tests: import "jest" test("good", () => { expec ...

Issue encountered with redux-toolkit's createAsyncThunk functionality

Here is how I implemented the deleteDirectories method in redux: export const deleteDirectories = createAsyncThunk( "directories/deleteDirectories", async (id, thunkAPI) => { try { const response = await axios.delete(`${url}direc ...

What is the best way to display just the selection outcome?

Currently, my code displays a full list of clinics. When I select a province in the dropdown menu, it only shows the clinics located in that specific province. I would like to modify this behavior so that the full list of clinics is not visible initially ...

Tips for managing errors when utilizing pipe and mergemap in Angular

In the code snippet provided, two APIs are being called. If there is an error in the first API call, I want to prevent the second API call from being made. Can you suggest a way to handle errors in this scenario? this.userService.signUp(this.signUpForm.v ...

Using jQuery in Angular, you can add a div element to hidden elements by appending

So, I have a hidden div that I want to show on button click. And not only do I want to show it, but I also want to append another div to it. The show and hide functionality is working fine, but the appending part seems tricky when dealing with hidden eleme ...

Can we create a generic constraint that utilizes an index, be it a type or an object?

I am currently generating client models (Entities) along with their corresponding Primary Keys. My goal is to create a method signature where, based on the Entity provided, the second parameter should be its Primary Key only. The specific use of types an ...

Learn the proper way to write onClick in tsx with Vue 2.7.13

current version of vue is 2.7.13 Although it supports jsx, I encounter a type error when using onClick event handling. The type '(event: MouseEvent) => Promise<void>' cannot be assigned to type 'MouseEvent' Is there a correct ...

The error message "Property 'showUserDropdown' is not found on type '{}'.ts" indicates that the specified property is not present in the defined

While creating a basic Vue component, I encountered an error in the IDE regarding the {{ showUserDropdown }} with the message: Property 'showUserDropdown' does not exist on type '{}'.ts Despite adding it to data, <template> &l ...

typescript throwing an unexpected import/export token error

I'm currently exploring TypeScript for the first time and I find myself puzzled by the import/export mechanisms that differ from what I'm used to with ES6. Here is an interface I'm attempting to export in a file named transformedRowInterfac ...

Unexpected behavior encountered when using TypeScript type declarations

I am currently working on a Gatsby side project incorporating Typescript for the first time. I initially expected Typescript to behave similarly to PHP type declarations, but I have encountered some unforeseen issues. Despite feeling confident in my Typesc ...

TypeScript: Unidentified reference to 'this' within the class

typescript version: 3.9.2 The goal is to define an interface constraint that permits only non-functional member keys on the class type NonFunctionKeys<T extends {}> = { [K in keyof T]-?: T[K] extends Function ? never : K }[keyof T]; class MyClas ...

The implementation of CommonJS modules allows for efficient modularization

While using Nx for my Angular workspace, I noticed something that sparked a question in my mind. Why is it necessary to use CommonJS modules in all tsconfig.spec.json files for libs? Looking at Nx examples, I observed that not all libs include it, only app ...