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

What is the best way to change the height of a div element as the user scrolls using JavaScript exclusively?

Coding with JavaScript var changeHeight = () => { let flag = 0; while(flag != 1) { size += 1; return size; } if(size == window.innerHeight/2){ flag == 1; } } var size = 5; document.body.style.height = &qu ...

Ways to identify when a file download has finished with the help of javascript

let pageUrl = "GPGeneration_Credit.ashx?UniqueID=" + __uniqueId + "&supplierID=" + supplierID + "&CreditID=" + OrderIds; window.open(pageUrl); // Want to check if the file download is complete and then refresh the page location.r ...

Exploring the power of Vue3 with reactive nested objects and the inclusion of

It seems like I've encountered a bit of a challenge... Perhaps a bug in Vue3 with Typescript and the composition API, or maybe I'm missing something. I'm facing an issue where I'm not getting any intellisense in my IDE (Webstorm) when ...

Executing Enter Key and Button Simultaneously with JavaScript: Step-by-Step Guide

I need assistance understanding how to simultaneously trigger the enter key and button in this code. When the value is entered into the input field, it should trigger both the enter key and the button "Enter" at the same time. Additionally, after pressing ...

Create a function that is identical to the original, but omits the final

I am currently working on defining a type B that functions similarly to type A, but without the last parameter. I have attempted the solution below, however, it is still requiring 2 parameters instead of just one. type Callback = (msg: string) => void; ...

Node.js and MySQL: Troubles with closing connections - Dealing with asynchronous complexities

I am currently working on a Node program to populate my MySQL database with data from files stored on disk. While the method I'm using seems to be effective, I am facing challenges in ensuring that asynchronous functions complete before ending the con ...

Verify in typescript if type A is equal to either type B or type C

Within one specific file, there is a structured code block like the following: export const _total = { a: '', b: '', c: '', d: '', e: '', f: '', } type TotalKeysType = typeof _all; ex ...

Are you experiencing a clash among various JS files in your WordPress installation?

I'm in a bit of a bind here. I've been tasked with working on a Wordpress website for a friend, using a free theme that he provided. Naturally, he wants some modifications made, so I've been editing the theme accordingly. The theme relies on ...

React Hooks encountering issues with keydown/up events functionality

Currently, I am in the process of implementing arrow-based keyboard controls for a game that I have been developing. In order to stay updated with React, I decided to utilize function components and hooks. To showcase my progress, I have put together a dem ...

Master the art of horizontal scrolling in React-Chartsjs-2

I recently created a bar chart using react.js and I need to find a way to enable horizontal scrolling on the x-axis as the number of values increases. The chart below displays daily search values inputted by users. With over 100 days worth of data already, ...

Developing an if-else statement to showcase a different div depending on the URL

Having trouble with an if/else statement to display one div or another based on the URL: No matter what I try, only "Div 1" keeps showing. Here's my code snippet: <script> if (window.location.href.indexOf("pink") > -1) { document.getElemen ...

Shortening a jQuery If-Else Statement in JavaScript

I am working on a snippet of code and need some help. Here is the code: <script type="text/javascript"> $(window).load(function() { if(!$.browser.msie){ $('#myDiv').animate({opacity: 1}, 300); } else if ($.browser.msie) { ...

A recursive approach for constructing a tree structure in Angular

Currently, I am working on a project involving the implementation of crud functions. To display the data in a tree-like structure, I am utilizing the org chart component from the PrimeNg library. The data obtained from the backend is in the form of an arra ...

The PHP sorted array loses its order when encoded into JSON and then sorted in JavaScript

In my PHP code, I have two arrays that I need to work with. The first array is sorted using the arsort() function like this: arsort($array1); After sorting, I output the contents of both arrays like so: foreach ($array1 as $key => $val) { $output ...

Is using float:right making the jquery slide toggle dropdown div (triggered by hover) appear glitchy?

Utilizing jQuery's slidetoggle and hover functions, I have successfully implemented a dropdown feature in my div. Within this div, there is various information displayed including the date, a note counter, and three buttons. The first two are Tumblr ...

What are the best ways to keep a django page up to date without the need for manual

Currently, I am in the process of developing a Django website focused on the stock market. Utilizing an API, I am pulling real-time data from the stock market and aiming to update the live price of a stock every 5 seconds according to the information pro ...

Cookies set by ExpressJS Cookie-Parser do not remain across multiple HTTP requests

Currently, I'm utilizing Cookie - Parser in conjunction with express.js. Within my express config file, I have included app.use(cookieParser()). In the main (app.js) file for the server, I am setting the cookie whenever there's a POST request to ...

Error message: Invariant Violation: Portal.render() being caused by semantic-ui-react Basic Modal

As part of enhancing an existing React component, I attempted to include a basic modal (link to documentation). Everything was working well without the modal, but once I added it in following the semantic-ui-react guidelines, I encountered a runtime error ...

Removing an object from an array if it does not exist in another array: A step-by-step

Looking to remove an object from an array if it's not present in another array. After doing some research, I came across a similar question on this link, but with a different array source. Below is the example from the link: var check = [1, 2, 3]; ...

Arrange items by their keys while keeping their current values in order to correspond to the array sequence

I have two sets of data. First one is in the form of (footerMenuOptions): [{Home: true}, {About: false}, {Features: false}, {Contact: false}]  The second set is in the form of (this.navbarMenuOptions): ["Home", "About", "Features", "Contact"] Occasio ...