How can one efficiently locate the suitable dynamic path resource within an array of resources?

In my scenario, I am dealing with an Array of resources that includes a dynamic resource like "guides/:guideId/packages" and a currentURL (guides/GUIDE007/packages):

const resources = ["guides", "guides/files", "guides/:guideId/packages"];
const currentURL = "guides/GUIDE007/packages";

const findMatch = (resources, currentURL) => { return ... ?? }  

const matchingResource = findMatch(resources, currentURL);
console.log(matchingResource) // guides/:guideId/packages

What is the most effective method for identifying a match in the array that corresponds to the resource format, given that the currentURL aligns with a resource?

Answer №1

Before diving into building your own route matching implementation, consider utilizing a library designed for this purpose. However, if you're interested in creating your own solution, here's a sample implementation that transforms resource strings into regular expressions for testing against the current URL.

const resources = ["guides", "guides/files", "guides/:guideId/packages", "guides/packages/:packageId"];
const currentURL1 = "guides/GUIDE007/packages";
const currentURL2 = "guides/packages/PKG007";

const getResourceMatch = (resources, currentURL) => {
  return resources.find(r => {
    const regexStr = '^' + r.replace(/(:\w+)/g,'[\\w-]+') + '$';
    const regex = new RegExp(regexStr);
    return regex.test(currentURL);
  })
}  

const resourceMatch1 = getResourceMatch(resources, currentURL1);
const resourceMatch2 = getResourceMatch(resources, currentURL2);

console.log(resourceMatch1) // guides/:guideId/packages
console.log(resourceMatch2) // guides/packages/:packageId

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 was the reason for the failure of my different sorting method?

I attempted to create a sorting algorithm without referring to any other code or resources. However, I am puzzled as to why my code doesn't produce any output. It seems to run for a while and then abruptly stop. I'm seeking guidance on where I m ...

Ways to dynamically retrieve a key value pair in JavaScript and React

I am currently working with a spreadsheet element where the cell values are stored in an object structure like this: localCells = {A1: {input: 'hi', value: 'world'}, A2: {input:'how', value:'you?'}} The object is q ...

Unveiling the Magic: Enhancing Raphaeljs with Interactive Click Events on a Delicious Slice of the

I'm having trouble responding to a click event on each slice of a Raphael Pie Chart. I've tried implementing the code below, but it doesn't seem to be working. The code is just two lines, commented as "My Code", in the example from the offic ...

Searching for a Mongoose Model by utilizing a field from a separate Schema

Let's say I have two schemas - User and Post. User schema includes an array of post _ids, and the Post schema has an attribute indicating if it is an active post, labeled as is_active. So, the goal is to filter Users who have at least one active post ...

Direct a collection of memory addresses to an assortment of multiple arrays

Exploring the concept of arrays of arrays, I am attempting to point to such a structure for learning purposes. The following code snippet demonstrates my approach: int Arr[6][6]; int (*ptr)[6][6]; ptr = &Arr; Is this setup correct? (EDIT: I want ...

Creating a Composite of Several Boxes in THREE.js

My goal is to display multiple boxes together in a specific structure shown in the image I have attached. I am interested in testing the GPU limitations by increasing the number of boxes, and then later on, I will focus on optimization. The framework I am ...

Enable a module for testing in a controller using Jasmine through Resharper

I have successfully managed to test a controller using jasmine through PhantomJs using Resharper 9.2 as a test runner. To set up Resharper, I followed the instructions provided on . The test runs smoothly if the controller does not specify the modules it ...

Preserve jQuery-enhanced webpage changes permanently

I am looking to permanently save modifications made on an HTML page using JQuery. I have come across suggestions about achieving this by sending an Ajax call and storing the data in a database table. However, I am unsure about what exactly needs to be save ...

Initial Year Setting for MUI X datepicker

For a project I am working on with my client, they have requested that the datepicker in MUI X default to the year 2023. They would like the datepicker to automatically display the year 2023 with the option for them to change it if needed, as most of the d ...

"electron-builder - initially designated for building app for Mac only, but now configured to build for both Mac

This is my first attempt at creating an electronjs app, so I may not have a full grasp on what I'm doing. I've been following the instructions on GitHub and also this guide from Medium. Here's a snippet of my package.json: { (package.jso ...

Updating the minimum date based on the user's previous selection using React JS and Material UI

In my material UI, I have two date pickers set up: From Date - <KeyboardDatePicker value={initialDateFrom} disableFuture={true} onChange={handleFromDateChange} > </KeyboardDatePicker> To Date - <KeyboardDatePicker value={initialDateTo} ...

Uncovering the User's Browser Specifically for UC-Mini and Opera-Mini

I'm in need of a script that can identify if the user's browser is uc-mini or opera-mini. These particular browsers do not support the "transition" feature. Therefore, when this specific browser is detected, I would like to deactivate the "trans ...

Effortless method for distributing NPM-loaded modules among various Browserify or Webpack bundles

Feeling frustrated trying to find a straightforward way to share code, required via NPM, across multiple Browserify or Webpack bundles. Is there a concept of a file "bridge" that can help? I'm not concerned about compile time (I know about watchify), ...

Having trouble getting my Leaflet map to display even after meticulously following the quick-start guide

I am experiencing an issue where the map is not displaying at all, leaving a blank space where it should be. Despite following Leaflet's quick-start guide, I have been unable to determine the cause of this problem. Here is the code that I currently h ...

Updating the title with respect to the current route in AngularJS 1

Is it possible to dynamically change the title displayed in a header based on the current route provided by the router, even when outside of the controller scope? For example, I have a mainMenu controller that is loaded when a specific route is called. The ...

Transform two fixed elements into dynamic elements using JQuery

Is there a way to replace two static elements in the table <tr class="item-row"> with data from an ajax call instead of just appending to them? Currently, I am using this javascript line to append: $(".item-row:last").after('<tr class="item- ...

The method Polygon.getTransformedVertices() is failing to return the desired array in LibGdx

I'm facing a rather perplexing issue that I can't seem to wrap my head around. Within my Helper class, there is a method called drawStar(): public void drawStar(Star star) { shapeRenderer.begin(ShapeType.Line); shapeRenderer.setColor ...

Steps to trigger an alert when the entered quantity exceeds the current stock levels

After developing an IMS System, I encountered a problem where my stock is going into negative figures. To resolve this issue, my primary goal is to trigger an alert whenever the quantity entered by a user exceeds the available stock. For example, if a us ...

Issue with Fat-Free Framework and Abide AJAX form submission malfunction

Currently, I am utilizing Foundation 5.5.3 and Abide form validation in order to facilitate site registration. This is reflected in my Javascript code below: $('form#register').on('valid.fndtn.abide', function() { var data = { ...

The intersectObjects function is failing to retrieve the object from the OBJMTLLoader

Within my scene, I've introduced a new object along with several other cubes. To detect collisions, I'm utilizing the following code snippet that fires a Ray: var ray = new THREE.Raycaster(camera.position, vec); var intersects = ray.intersectObj ...