Incorporating regular expressions to extract a specific string from a URL is a requirement

Can anyone assist with extracting a specific string using regex in TypeScript?

I have the following URL: https://test.io/content/storage/id/urn:aaid:sc:US:8eda16d4-baba-4c90-84ca-0f4c215358a1;revision=0?component_id=e62a5567-066d-452a-b147-19d909396132

I need to extract this string: urn:aaid:sc:US:8eda16d4-baba-4c90-84ca-0f4c215358a1, which always starts with "urn" and ends with a letter or number.

Could someone please provide guidance on how to achieve this using typescript?

I attempted the following code but received a null value. Any suggestions are appreciated!


function extractAssetIdFromUrl(url: string) {
    // Regular expression to match the desired pattern
    const regex = /urn[\w-]+/;
    
    // Use the regex to find the match in the URL
    const match = url.match(regex);

    // Check if there is a match and return it, otherwise return null
    return match ? match[0] : null;
}

Answer №1

is a fantastic resource for understanding and breaking down regex patterns.

The provided regex will fulfill the desired functionality based on the example pattern given:

/urn:(?:[^:]+:)*[a-z0-9-]+/ig

If you wish to extract this pattern from the sample URL string provided, you can achieve it like this:

const url = 'https://test.io/content/storage/id/urn:aaid:sc:US:8eda16d4-baba-4c90-84ca-0f4c215358a1;revision=0?component_id=e62a5567-066d-452a-b147-19d909396132';
const urnId = /urn:(?:[^:]+:)*[a-z0-9-]+/ig.exec(url)[0];
// = 'urn:aaid:sc:US:8eda16d4-baba-4c90-84ca-0f4c215358a1'

However, consider extracting the path from the URL first as URLs may contain query strings with patterns that match this, leading to unintended results.

Additionally, some have pointed out the presence of a semicolon delimiter in the URL, which could simplify your task if it consistently appears (potentially negating the need for regex).

Answer №2

It seems that your identifier is terminated with a semicolon, so I suggest using a regular expression for "starts with 'urn:'", and "followed by everything except ';'"

const  url = ` https://test.io/content/storage/id/urn:aaid:sc:US:8eda16d4-baba-4c90-84ca-0f4c215358a1;revision=0?component_id=e62a5567-066d-452a-b147-19d909396132`;

const match = url.match(/\/(urn:[^;]+);/);
if (match) console.log(match[1]);

Make sure to include this code in your project for proper identification.

Answer №3

Start by isolating the final segment of the path. This allows for a direct comparison with the necessary characters, without needing to consider the query string or any other URL component.

function retrieveIDfromURL(url) {
  // meeting the specified criteria
  // "The string will always start with a urn and end with a letter or number"
  const rx = /^urn[a-z0-9:-]*[a-z0-9]/i;
  
  const lastName = new URL(url).pathname.split('/').at(-1);
  return lastName.match(rx)?.[0] ?? null;
}

console.log(
  retrieveIDfromURL(
    "https://test.io/content/storage/id/urn:aaid:sc:US:8eda16d4-baba-4c90-84ca-0f4c215358a1;revision=0?component_id=e62a5567-066d-452a-b147-19d909396132",
  ),
);

console.log(
  retrieveIDfromURL(
    "https://example.com/foo/bar/baz",
  ),
);

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

Utilizing variable values in Google Charts with AngularJS

Hello everyone, I am attempting to display a chart using data obtained from an API. The output of the API is in the form of List<String> and not in JSON format. Here is the snippet of my JS file: google.load('visualization', '1', ...

Discover the exclusive Error 404 dynamic routes available only in the production version of NEXT13! Don

Hey everyone, I'm encountering an issue with NEXT's dynamic routing (Next 13). My folder structure looks like this: - user/ -- [id]/ --- page.js It works fine in dev mode but not in production. What am I trying to do? I've created a "page ...

Ways to initiate animation using CSS when the page loads

Is there a way to initialize the counter on page load? Even though I was successful in making it start on hover, I couldn't figure out how to make it work when the page loads. Here is the JavaScript code: var root = document.querySelector(':root ...

Extract data from dynamically loaded tables using PhantomJS and Selenium Webdriver

I've been informed by everyone that I should be able to retrieve the table content using PhantomJS when working with JavaScript. However, despite my attempts, I have not been successful. My expectation was to obtain the table from the website Page 1 ...

Tips for executing a function on a specific class selector using the document.getElementsByClassName method

When I click on a specific class, I want to implement a fade-out function in JavaScript. However, I am struggling to make a particular class fade out successfully. I attempted to use the this keyword, but it seems like I might be using it incorrectly bec ...

Issue in Ionic 2: typescript: The identifier 'EventStaffLogService' could not be located

I encountered an error after updating the app scripts. Although I've installed the latest version, I am not familiar with typescript. The code used to function properly before I executed the update. cli $ ionic serve Running 'serve:before' ...

Changes to the className of a React component will trigger a re-render of

When the className of the parent changes, React children will re-render. import React from 'react'; import { useSelector } from 'react-redux'; import items from './ItemsList.js'; import Item from './Item'; import &ap ...

13 Helpful Tips for Resolving Hydration Failure Due to Discrepancy in Custom Dropdown Display between Server and UI

Recently, I embarked on a project utilizing the latest version 13 of Next.js with its new app directory feature. As I integrated a custom dropdown into one of my pages, an error surfaced: "Hydration failed because the initial UI does not match what was ren ...

Performing an HTTP GET Request in Node.js or Express.js

Currently, I am working with express.js and require assistance in making an HTTP GET request to retrieve JSON data. Can anyone recommend some reliable node js/express js modules or libraries that can help me with performing get/post requests? ...

Displaying a Next.js component depending on the environment setting

Having trouble displaying a maintenance message to users based on an environment value. In my .env.local file, I have the following value set: NEXT_PUBLIC_SHOW_MAINTENANCE=true This is how my page is structured: const Index = () => { const showMai ...

The full height of the image cannot be captured by html2canvas

It baffles me that html2canvas is failing to capture the full height of the div. html2canvas($container, { height: $container.height(), onrendered: function(canvas) { var data = canvas.toDataURL('image/png'); ...

A versatile Material UI paper that adjusts its dimensions dynamically

Utilizing Material-UI's Paper component (https://mui.com/components/paper/), I've encountered a scenario where the content within the Paper element needs to be dynamic. <Paper className="modal" elevation={3}> ...Content </Paper ...

A tutorial on how to switch classes between two tabs with a click event in Vue.js

I am having an issue with my spans. I want to implement a feature where clicking on one tab changes its color to red while the other remains gray. I have tried using class binding in my logic but it's not working. How can I solve this problem and make ...

Create custom error messages for loopback instead of using the default ones

I am attempting to customize the default error messages provided by loopback. Here is my approach: server/middleware.json: { "initial:before": { "loopback#favicon": {} }, "initial": { "compression": {}, "cors": { "params": { ...

Is it possible to include a base url for imports in React JS?

Conventional method for adding imports: import Sample from ‘../../../components/signup’ I want to simplify imports by removing the front dots and slashes: import Component from ‘components/signup’ Is there a way to set a base URL for imports to ...

"Exploring the capabilities of Rxjs ReplaySubject and its usage with the

Is it possible to utilize the pairwise() method with a ReplaySubject instead of a BehaviorSubject when working with the first emitted value? Typically, with a BehaviorSubject, I can set the initial value in the constructor allowing pairwise() to function ...

jQuery counter no longer updates when scrolling

I'm having trouble with my jQuery counting function when using the scroll feature on a specific div ID. The numbers freeze if I keep scrolling before they finish updating on the screen. Whenever I scroll to the defined div ID, the counting function k ...

One way to achieve the same functionality as onclick in an Ajax call using

I have two JSPs. In the first JSP, I am making an ajax call and receiving data (Ajax body) from the second JSP. However, I am unsure of how to execute jQuery when an argument is present in the function. Everything works fine without an argument. In the ...

Is it possible to implement the splice() method within a forEach loop in Vue for mutation

Hey there! I'm looking for a more efficient way to replace objects that match a specific index with my response data. Currently, I'm attempting to use the splice() method within a forEach() loop in Vue.js. However, it seems to only remove the obj ...

Angular 4, Trouble: Unable to resolve parameters for StateObservable: (?)

I've been working on writing unit tests for one of my services but keep encountering an error: "Can't resolve all parameters for StateObservable: (?)". As a result, my test is failing. Can someone please help me identify and fix the issue? Here& ...