What is the best way to substitute unpredictable dynamic variables on-the-fly?

I am working with a .js file that contains a config structure similar to this:

genGetLocations:{
   data_url:'restaurants/{var1}/tables/{var2},
}

This is just one example. Some configurations may have data_url with more than two dynamic variables. In the .vue file, after obtaining the data_url, I will have two IDs that need to be inserted into var1 and var2 to form the final REST API URL for the request.

Challenge: It's uncertain how many variables each data_url will contain or where they will be placed within the data_url. Therefore, in the .vue files, when I get the IDs, I need to replace them in the data_url accordingly.

Answer №1

Whether your IDs are structured within an array or object, there are different approaches to consider:

const data = 'restaurants/{var1}/tables/{var2}';
const idsArray = [101, 102];

console.log(
  data.replace(/\{var(\d+)\}/g, (substr, idx) => idsArray[parseInt(idx) - 1])
);

const data = 'restaurants/{var1}/tables/{var2}';
const idsObj = {
  var1: 101,
  var2: 102
};

console.log(
  data.replace(/\{(var\d+)\}/g, (substr, key) => idsObj[key])
);

If you prefer using arbitrary keys:

const data = 'restaurants/{foo}/tables/{bar}';
const idsObj = {
  foo: 101,
  bar: 102
};

console.log(
  data.replace(/\{(.*?)\}/g, (substr, key) => idsObj[key])
);

Answer №2

Searching for every instance of {} in the URL provided is essential here. The placeholders can take various forms, such as {var1}, or {string2}.

To accomplish this task, consider the following code snippet:

var info = {"genGetLocations": {
   "data_url": "restaurants/{var1}/tables/{var2}"
}};

var ids = ["test1", "test2", "test3"];
var regexp = /\{.*?\}/g;
var results = info.genGetLocations.data_url.match(regexp);
var replacedString = info.genGetLocations.data_url;
results.forEach(function(result, index) {
  replacedString = replacedString.replace(new RegExp(result,"g"), ids[index]); 
});

console.log(replacedString);

Answer №3

Why not give this a try?

String.prototype.formatUnicorn = String.prototype.formatUnicorn || function () {
    var template = this.toString();
    if (!arguments.length)
        return template;
    var argumentType = typeof arguments[0],
    params = "string" == argumentType || "number" == argumentType ? Array.prototype.slice.call(arguments) : arguments[0];
    for (var key in params)
        template = template.replace(new RegExp("\\{" + key + "\\}", "gi"), params[key]);
    return template
}

/** Example Code 
genGetLocations:{
   data_url:'restaurants/{var1}/tables/{var2},
}**/
console.log('restaurants/{var1}/tables/{var2}'.formatUnicorn({'var1':'test1','var2':'test2'}))

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

Saving numerous files with Promises

There is a Node URL (created using Express) that enables users to download static images of addresses. The calling application sends a request to the /download URL with multiple addresses in JSON format. The download service then calls Google Maps to save ...

a guide on creating a dynamic hierarchical menu using vue.js

######################## UPDATED ######################## As per the response from @Criss, it seems that the method didn't work because there is a discrepancy between the child item and parent item. https://i.stack.imgur.com/jzHZR.png A simple item ...

Angular2 scripts are failing to load in the web browser

Setting up my index page has been more challenging than I anticipated. Take a look at my browser: https://i.stack.imgur.com/L4b6o.png Here is the index page I'm struggling with: https://i.stack.imgur.com/Op6lG.png I am completely stumped this tim ...

Tips for avoiding automatic updates to .js scripts after pressing F5

Is there a method to stop a JavaScript script from resetting when the user refreshes the page? For instance, if I have a picture slider that is constantly changing images, I would like the script to continue where it left off instead of starting over wit ...

Discover which npm module includes the lodash dependency

I've encountered a peculiar situation while using webpack to create a production bundle for my application. Even though I haven't explicitly installed `lodash` and it's not listed in my package.json file, I noticed that it's being added ...

When faced with the error message "Typescript property does not exist on union type" it becomes difficult to assess the variable

This question is a continuation of the previous discussion on Typescript property does not exist on union type. One solution suggested was to utilize the in operator to evaluate objects within the union. Here's an example: type Obj1 = { message: stri ...

Error: Trying to call an undefined function

Having trouble with an error on this line: $("#register-form").validate. Can anyone offer assistance? Furthermore, if I write this script, how should I incorporate it into the form? Will it function without being called? <script type="text/javascript ...

The ternary operator is malfunctioning when it comes to the condition

I've encountered an issue while trying to integrate a custom MUI button into my project. My goal is to have the button enabled only when 2 specific objects are not empty, otherwise it should remain disabled. Despite my efforts, the code I've writ ...

Is it possible for AJAX to update a button's argument?

After successfully using AJAX to extract a data value from a button click, I am now looking to pass this value as an argument to another button on the same page. Is there a way to achieve this seamlessly? Sample code from test.html: <a href="#" onClic ...

A glitch in showcasing the hello world example in Node.js with express

I've been diving into learning node.js and I'm eager to use the express framework. However, I hit a roadblock when trying to run a simple "hello world" example from the expressjs.com website. Instead of seeing the expected output, I encountered a ...

Sending a parameter to a different function (on a separate webpage)

At the start of my webpage, there are two radio buttons on the first page, each with its own value. Upon clicking a link to move to the second page, a for loop is activated to grab the value of the selected button. The script has been tested and works as e ...

Encountering 404 Error in Production with NextJS Dynamic Routes

I'm currently working on a next.js project that includes a dynamic routes page. Rather than fetching projects, I simply import data from a local JSON file. While this setup works well during development, I encounter a 404 error for non-existent pages ...

CoffeeScript is failing to run the code

I'm attempting to use a click function to alter the CSS code and then run a function. Here is my current code: ready: -> $("#titleDD").click -> $("#titleDD").css('text-decoration', 'underline'); $("#catDD").css( ...

Retrieving all selected checkboxes in AngularJS

I am a beginner in angular js and here is my template: <div class="inputField"> <h1>Categories</h1> <div> <label><input type="checkbox" id="all" ng-model="all" ng-change="checkAll();" ng-true-value="1">A ...

Guide to switching between 3 classes with mouseover using JavaScript

Currently, I am dealing with an unordered list that contains 4 items. The goal is to have the list grow to 100% of its width when hovered over, while all 'noun hovered li' items should shrink to a width of 0%. Once the cursor leaves, everything s ...

Comparing obj.hasOwnProperty(key) with directly accessing obj[key]

Consider the scenario where I need to determine if a property exists within an Object. A comparison between two methods caught my attention: if(object.hasOwnProperty(key)) { /* perform this action */ } OR if(object[key]) { /* perform this action */ ...

When trying to authorize my channel, the JSON data is coming back as a blank string

I've encountered an issue with my JavaScript code: Pusher is throwing the error message "JSON returned from auth endpoint was invalid, yet status code was 200. Data was: ", indicating empty data. I have double-checked the broadcasting service provider ...

The dropdown on my website is malfunctioning

There seems to be an issue with my dropdown button. Previously, it only appeared when clicking on a specific part of the button. I attempted to resolve this problem but unfortunately, the dropdown no longer works at all and I am unable to revert my changes ...

The Node.js JSON string displays as "[object Object]" in the output

Front End // js / jquery var content = { info : 'this is info', extra : 'more info' } $.ajax({ type: 'POST', url: '/tosave', data: content }); Node // app.js app.post('/tosave', funct ...

Modify data in an array using Vuex

When working with my Vuex mutation, I am trying to replace an element in an array within the state. The code snippet below illustrates what I am attempting to do: UPDATE_MAILING(state, mailing) { let index = _.findIndex(state.mailings, {id: mailing.id ...