Isolating the value from a Typescript regex match rather than capturing the entire

Suppose we have a URL like '/mentor/33' as an example

To manipulate this, I use regex: buildRegex('/mentor/:id');

'/mentor/:id' is transformed into '/mentor/[^/]'

const PATH_PARAM = {
    PREFIX: ':',
    REGEX_IDENTIFIER: '/:[^/]+',
    REGEX_REPLACER: '/[^/]+',
};

private buildRegex(path: string) {
        return this.ensureLeadingSlash(path).replace(
            new RegExp(PATH_PARAM.REGEX_IDENTIFIER, 'g'),
            PATH_PARAM.REGEX_REPLACER
        );
    }

How can I extract just the value 33 from '[^/]'

If I implement this function

private matchRegex(routeLink: string, routeRegex: string) {
        const match = routeLink.match(new RegExp(routeRegex, "g"));
        return match?.[0];
    }

then I end up with /mentor/33 instead of only 33. I am seeking a more generic solution.

Answer №1

To improve the matching process, encapsulate the replaced pattern within a group and reference that group instead of using [0] post matching. Depending on your specific circumstances and the dynamic nature of the content, decide whether the group should be included in the PATH_PARAM or generated dynamically whenever buildRegex is invoked.

Avoid using the global flag if you are only performing the match once.

const PATH_PARAM = {
    PREFIX: ':',
    REGEX_IDENTIFIER: '/:[^/]+',
    REGEX_REPLACER: '/[^/]+',
};
const buildRegex = (path) => {
    return path.replace(
        new RegExp(PATH_PARAM.REGEX_IDENTIFIER),
        `(?<pathinfo>${PATH_PARAM.REGEX_REPLACER})`
    );
};
const pattern = buildRegex('/mentor/:id');
const matchRegex = (routeLink, routeRegex) => {
    const match = routeLink.match(routeRegex);
    return match?.groups.pathinfo;
}
console.log(matchRegex('/mentor/33', pattern));

If the initial / is causing issues, remember that both your REGEX_IDENTIFIER and REGEX_REPLACER include a /. You can either remove the first character afterwards, alter the REGEX_IDENTIFIER and REGEX_REPLACER to exclude the slashes, or directly incorporate the group into the PATH_PARAM object instead of generating it on-the-fly.

const PATH_PARAM = {
    PREFIX: ':',
    REGEX_IDENTIFIER: '/:[^/]+',
    REGEX_REPLACER: '/(?<pathinfo>[^/]+)',
};
const buildRegex = (path) => {
    return path.replace(
        new RegExp(PATH_PARAM.REGEX_IDENTIFIER),
        PATH_PARAM.REGEX_REPLACER
    );
};
const pattern = buildRegex('/mentor/:id');
const matchRegex = (routeLink, routeRegex) => {
    const match = routeLink.match(routeRegex);
    return match?.groups.pathinfo;
}
console.log(matchRegex('/mentor/33', pattern));

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

Changing the date format in Angular 2

Currently facing an issue with changing my date format from yyyy-mm-dd to dd-mm-yyyy in Angular v 2.4.0. Unfortunately, I am unable to utilize the moment.js library for this task. ...

Is there a way to redirect components within a different component without altering the URL?

Imagine you have an Angular 5 project with routings, such as /home, /landing-page, etc. Let's say your landing page has the URL localhost:4200. On this page, you want to create a login panel with fields for username and password, a sign in button, and ...

Is there a method in TypeScript to create an extended type for the global window object using the typeof keyword?

Is it possible in TypeScript to define an extended type for a global object using the `typeof` keyword? Example 1: window.id = 1 interface window{ id: typeof window.id; } Example 2: Array.prototype.unique = function() { return [...new Set(this)] ...

How to retrieve a typed object from mongoose

I am currently developing a nodejs application using typescript and have recently incorporated mongoose for interacting with the mongo db. However, I am facing a challenge in obtaining the typed object from the findById method in mongoose. Is there a wor ...

Using TypeScript to implement a nested static class with enforced generic type constraints

As an illustration, let's consider a basic linked list class in TypeScript version 3.7.5. A LinkedList<T> is composed of a series of ListNode<T>, where the type variable T remains consistent between them. In this scenario, a private static ...

Navigating to Null in Internet Explorer 11 (in certain versions) following a successful login using AAD 2 Authentication on Angular 2

Experiencing a Redirect Issue in Internet Explorer 11 (in certain versions) Following Successful Authentication with AAD 2 in Angular 2. Functioning as Expected in Chrome and Other Browsers. When accessing the home page at http://localhost:1234, it shoul ...

Using the "@" symbol to import a custom class in Typescript

There have been instances where we import a package like this import { SharedModule } from '@shared/shared.module'; In this case, @shared refers to the folder within our project /src/shared I am trying to find a way to avoid importing my clas ...

Troubleshooting Issue with Angular Fixture DebugElement's Query By class Function Not Finding Elements

Following the recommendations in the Angular.io Framework Testing documentation, I have been experimenting with using DebugElement query in combination with Angular Testbed + Karma test Runner. I have implemented a jqwidgets Tree component that generates l ...

Create an Angular library that incorporates a TypeScript dependency into the compilation process

Within my Angular lib, residing in an Nx workspace... The lib relies on another local lib for shared TypeScript code. The path to the shared lib is set in the tsconfig paths configuration: "paths": { "@myOrg/sharedLib": ["lib ...

The element '<selector>' is unrecognized and cannot be found

Before I proceed with my query: I have gone through similar questions with the same title and followed the given advice, but none of it has worked for me. Therefore, I have decided to create a new question. In my Angular project, I have one module and mul ...

Error message "net::ERR_CONNECTION_CLOSED" encountered in an Angular 2 Firebase application

After setting up my Node app and MongoDB on a DigitalOcean droplet and hosting my Angular App on Firebase, I encountered an issue. While I can connect to the Node backend from Postman and my locally running Angular App on port 4200, I faced an error when t ...

There is no index signature in AxiosStatic

As I convert a hook from JavaScript to TypeScript, I encounter the following error: (alias) const axios: AxiosStatic import axios Element implicitly has an 'any' type because type 'AxiosStatic' has no index signature. Did you mean to ca ...

including various duplicates of the identical component within the Angular application

Currently, I am diving into Angular through the fantastic "Tour of Heroes" application. As I progress through the stage involving multiple components, one interesting feature is to display hero details by simply clicking on a hero's name. I am intrigu ...

Encountering an error with the ".ts" file extension when attempting to execute a ts-node script

I am currently facing an issue while trying to execute a script that consists of two .ts files in a regular folder. One file contains the script, and the other has helper functions required to run it. Additionally, I am importing external libraries such as ...

What could be the reason why my Angular component is experiencing input issues?

I am facing an issue with my angular class: @Component({ selector: 'main-title', styleUrls: ['main_title.scss'], template: ` <ng-template> <div class="main-title"> <h2 [ngClass]="{&apo ...

Only the initial letter of the angular input is returned by the event

Question: Why is the event only capturing the first letter of the input form? Background: In an input form, users can type a string but the method I created to handle the event is only recognizing the first letter entered. For example, if someone types "h ...

Tips for effectively overriding a method in typescript

Why is this.fullName appearing empty in the show() method? class Person { protected name: string = ""; constructor(name: string) { this.makeSir(name); } makeSir(name: string) { this.name = "sir" + name; } } class M ...

Injecting services and retrieving data in Angular applications

As a newcomer to Angular, I am trying to ensure that I am following best practices in my project. Here is the scenario: Employee service: responsible for all backend calls (getEmployees, getEmployee(id), saveEmployee(employee)) Employees components: displ ...

Create a simulated API in Angular by utilizing JasonPlaceholder to retrieve information upon clicking a button

I am currently developing a dummy API using jsonplaceholder. I have managed to retrieve all posts after clicking a button, but now I want to display the user ID and title by default on page load. Additionally, when clicking on a post's title, I would ...

No results found in MongoDB query when using find method

Having an issue with an API call to my express server to retrieve employees working in the same location based on the location ID. Strangely, the API call returns an empty array while it functions correctly in the command-line interface. Definition of Emp ...