Replace a certain substring with the corresponding keys found in an object using JavaScript

I am currently working on a function within a project that is designed to replace instances of

/endpoint/{item.id}/disable/{item.name}
with /endpoint/123/disable/lorem when the function is provided with the URL and item details.

The item is expected to contain the keys id and name.

What is the most effective method for identifying items in the format of {item.KEY} and substituting them with item.KEY?

Answer №1

One efficient approach to tackle this challenge is by utilizing a function to handle regular expressions. I have made adjustments to your parameters to streamline the mapping process, but feel free to customize them as needed.

let url = '/api/{id}/info/{type}'; //Adjusted parameters for clarity

const data = { id: 456, type: 'example' };
url = url.replace(/{([^}]*)}/g, function (property) {
  let key = property.substr(1, property.length - 2);
  if (data[key])
    return encodeURIComponent(data[key]);
  else
    throw new Error('The property "' + key + '" is required but missing in the data object');
});

//console.log(url);

Check it out on JSFiddle: https://jsfiddle.net/3rd8bnx0/1/

Answer №2

If you are looking for an alternative to using eval, you can consider implementing a function like the one mentioned in this link:

var item = {
    id: 123,
    KEY: "lorem"
};

function pick(o, s) {
    s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    s = s.replace(/^\./, '');           // strip a leading dot
    var a = s.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            o = o[k];
        } else {
            return;
        }
    }
    return o;
}

After implementing the function, you can then use the following code snippet:

str.replace(/{.*?}/g, function(match){ // match {...}
    var path = match.substring(1,match.length-1); // get rid of brackets.
    return pick(scope, path); //get value and replace it in string.
});

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

Tips for effectively separating HTML and JavaScript for a cleaner code structure

Is it necessary and worth it to decouple HTML and JavaScript? In JavaScript logic, you always have to use some HTML elements... I know that in C#, you can decouple for easier maintenance and testing scenarios. ...

Implementing context menus on the Material-UI DataGrid is a straightforward process that can enhance the user experience

I am looking to enhance my context menus to be more like what is demonstrated here: Currently, I have only been able to achieve something similar to this example: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx The contextmenu ...

losing track of the requested parameters while working asynchronously with Firestore documents

Today is my first time experimenting with firestore and express. Here is the code snippet I am using: app.post('/api/create', (req, res) => { (async () => { try { console.log(req.body); //the above consle.lo ...

Execute Javascript Code Once Directive Has Finished Rendering the DOM for ShareThis

Within my Angular (1.3) application, I have a list of records being displayed using ng-repeat. The template includes a directive that contains ShareThis controls from ShareThis, which are activated once the DOM is loaded. Upon the initial load of the app, ...

Tips for obtaining the entire date and time on one continuous line without any breaks or separation

Is there a way to retrieve the current date and time in the format of years, months, days, hours, minutes, seconds, and milliseconds like this? 201802281007475001 Currently, I am getting something like: 2018418112252159 This is my code so far: var dat ...

There is no 'depto_modules.length' property in this row. How should I go about fixing this issue?

I have a table set up to display data from an associated table. The functionality is working fine, but I keep seeing a warning message when I apply certain filters: The warning states that the property depto_modules.length does not exist in the row. It ad ...

Click on the button to send the input field

Below you'll find an input field and a button: <input id="pac-input" class="controls" type="text" placeholder="Search! e.g. Pizza, Pharmacy, Post office"> <button id="new" class="btn btn-success">Submit</button> Currently, when te ...

The requested resource lacks the 'Access-Control-Allow-Origin' header in a basic HTML form

Can someone help me understand why I keep encountering this error in my basic HTML form? I am attempting to display XML data on my website to showcase news stories, but unfortunately, I keep getting stuck with this persistent error. Any assistance would ...

Error animation on client-side validation not resetting correctly

Incorporated a form validation and error display system utilizing TransitionGroup for animations. The flag issueVisible manages the visibility of the error message, while determineField() aids in identifying the field related to the error. The issue arise ...

The Jquery datepicker value from UIGRid is not being retrieved when attempting to submit the form

I have implemented a jQuery Datepicker in a UI-Grid cell with the following code: { name: 'RDD', displayName: 'RDD', cellTemplate:'<input type="text" class="datepicker" id="{{row.entity.PartID}}" ng-model="row.entity.RDD" ng ...

Character count in textarea does not work properly when the page is first loaded

As English is not my first language, I apologize in advance for any grammar mistakes. I have implemented a JavaScript function to count the characters in a textarea. The code works perfectly - it displays the character limit reducing as you type. However, ...

What causes the tweets' IDs to be altered by axios when parsing the response from the Twitter search API?

I am currently utilizing axios to send a GET request to the Twitter search API in order to fetch recent tweets that utilize a specific hashtag. To begin with, I ran tests on the twitter search API via Postman and noticed that the id and id_str tweet statu ...

Implementing a dynamic like functionality using Ajax in Django

I've created a new structure for the like button, but it's not functioning correctly. Here are the files I'm working with: models.py class Comment(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey(Pr ...

Testing for the presence of a child element within a parent component in React

Below is the structure of my component: const Parent = (props) => { return <div>{props.children}</div>; }; const Child1 = (props) => { return <h2>child 1</h2>; }; const Child2 = (props) => { return <h2>child 2 ...

The export of a corrupted "OffscreenCanvas" is prohibited

Currently, I am implementing a process where an ImageBitmap is passed into a web worker in order to render it on a canvas. Subsequently, a URL is generated for loading into THREE.js on the main thread. Within the main thread this.canvas = this.canvasEl. ...

Disabling cache in AngularJS is being overridden by Chrome's cache

I'm currently encountering an interesting caching issue while using Chrome. My angularjs service looks like this: var url = '/api/acts/' + accountId + '/policy/?filter=NEW_POLICY'; return $http({ ...

The ng-repeat directive is failing to properly iterate over a key-value pair when the key contains a special character such as

When using ng-repeat with key value pairs that contain special characters such as ($), it may not work properly. For example: <div ng-repeat="(key, value) in values">{{key}}</div> In this case, if the values object is defined as below: $sco ...

Applying a class change in Vue.js upon mounting

How can I make a button element with a .hover property trigger the hover animation as soon as the page loads? I want to apply a class to the button when the page is mounted and then remove it later. What is the best approach for this? I considered using a ...

Dividing the logic from the Express router while retaining the ability to utilize Express functionalities

As I embark on my journey of developing my first app using Node.js and Express, I have noticed that my router file is starting to get overcrowded with logic. It seems like there is too much going on in there. My solution to this issue is to pass a functio ...

Duplicate request submissions in ExtJs causing inefficiency

Trying to resolve an issue with my ExtJs table that handles remote filtering, sorting, and paging of data on the server. The problem arises when a default request is being sent alongside every other request: localhost/request?page=1&start=0&limit= ...