Using a JSON array, you can perform JavaScript replacements in a string by utilizing regular expressions

In order to replace all instances within {} with the corresponding data from a JSON array, I need to use a regex pattern that is case-sensitive.

The number of placeholders enclosed in {}s may vary depending on the page.

s ="<address><div>{Name}</div><div>{Address1}</div><div>{Address2}</div><div>{ZipCode} {City}</div><div>{State}</div><div>{Country}</div><div>{ContactName}</div></address>"

"DeliveryAddress":
        {
            "Id":5637169131,
            "Name":"some name",
            "Name2":null,
            "Address":"Somewhere street 12",
            "Address2":null,
            "City":"Heven",
            "ZipCode":"1111",
            "State":"FL",
                        "Country":"US",
            "VatNo":null,
            "ContactRecId":"Receiving Department",
            "ContactName":null,
            "ContactPhone":null,
            "ContactEmail":null,
            "DefaultShopDeliveryAddress":false,
            "DefaultServiceDeliveryAddress":false,
            "IsOneTime":false,
            "CaptureId":"00000000-0000-0000-0000-000000000000"
        },

Once completed, the matching elements in my JSON array should replace the corresponding {tag} placeholders.

For example:

<address><div>some name</div><div>Somewhere street 12</div><div></div><div>1111 Heaven</div><div>FL</div><div>US</div><div></div></address>

Answer №1

If you need to populate an address template with specific information, you can utilize the following code snippet:

template ="<address><div>{Name}</div><div>{Address1}</div><div>{Address2}</div><div>{ZipCode} {City}</div><div>{State}</div><div>{Country}</div><div>{ContactName}</div></address>"
DeliveryAddress = {
            "Id":5637169131,
            "Name":"some name",
            "Name2":null,
            "Address1":"Somewhere street 12",
            "Address2":null,
            "City":"Heven",
            "ZipCode":"1111",
            "State":"FL",
            "Country":"US",
            "VatNo":null,
            "ContactRecId":"Receiving Department",
            "ContactName":null,
            "ContactPhone":null,
            "ContactEmail":null,
            "DefaultShopDeliveryAddress":false,
            "DefaultServiceDeliveryAddress":false,
            "IsOneTime":false,
            "CaptureId":"00000000-0000-0000-0000-000000000000"
        };

for (var key in DeliveryAddress) {
  var formattedKey = new RegExp('{' + key + '}', "i");
  template = template.replace(formattedKey, DeliveryAddress[key]);
}
console.log(template);

RESULT:

<address><div>some name</div><div>Somewhere street 12</div><div></div><div>1111 Heaven</div><div>FL</div><div>US</div><div></div></address>

Answer №2

Implement a function called s_fill that utilizes the String.replace method with global and multiline flags:

function s_fill(s, dict) {
    for (var key in dict) {
        var regex = new RegExp('{' + key + '}', 'gm');
        s = s.replace(regex, dict[key]);
    }
    return s;
}

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

In the process of making a request with axios in an express server

Struggling with a simple call to an API using Axios with Express, and I can't figure out why it's always pending in the browser. Here is my route: var express = require("express"); var router = express.Router(); const controller = require("../. ...

Shift attention to the subsequent division after a correct radio option or text input has been submitted

I need to enhance the user experience on my form. When a user interacts with specific elements like hitting enter in a text input or clicking a radio button, I want to automatically focus on the next "formItem" division. My form structure is organized as ...

What is the best way to transform the format of an array output?

In my Ruby code, I'm working with an narray that is automatically generated and has the form [x,y], where x and y are both integers. My goal is to convert [x,y] into a specific type of string: "p\.x\.y" So far, I've been struggling t ...

Having trouble getting the onPress event to function properly on a custom button component in my React Native application

As a React Native beginner, I am currently working on a project where I am trying to create a custom button named "RoundedButton" using TouchableOpacity. However, when I attempt to trigger an event using onPress like , it does not seem to work for me. Here ...

From Transforming Tabular Parent-Child Data into Tree Structures

My sql table structure is similar to the one below. The rowId serves as the primary key and parentID indicates the rowID of the parent record: RowID ParentID Name 1 0 Fruit 2 1 Apple 3 1 Peach 4 0 Veggie 5 4 Corn 6 5 Sweet Corn I am look ...

I'm having trouble receiving a response after uploading an image on Cloudinary using React js

Once the image is uploaded using the API, it should return a response. However, I am not receiving any response through the API even after uploading the image. if (pic.type === "image/jpeg" || pic.type === "image/png") { const da ...

The default selection for React Material Multiselect items is not being chosen

Currently, I am working on implementing the React Material autocomplete component that includes a multiple-values checkbox. However, it seems like there is an issue with the defaultValue prop and the checkboxes example. Even though I set defaultValue to a ...

Difficulty in defining the header while using the submit hook in Remix 1.15

When I utilize the useSubmit hook to send a POST request, it appears that the header I specify is not being taken into account. Below is the code snippet for my submit function: submit('/dashboard/', { method: 'post', heade ...

In PHP, upload a .dat file so that it can be saved as a JSON file

I'm attempting to upload a .dat file and extract its content in JSON format. Here is the code I am using: HTML: <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="fileUpload"> < ...

Mocking Prisma in a NodeJS environment: A comprehensive guide

Despite my best efforts to follow the documentation, numerous tutorials, Stack Overflow answers, and more, I still can't seem to figure it out. How can I successfully mock a Prisma DB Connection? I want to conduct tests on my API for GitHub actions, b ...

Combining and removing identical values in JavaScript

I need to sum the price values for duplicated elements in an array. Here is the current array: var products = [["product_1", 6, "hamburger"],["product_2", 10, "cola"],["product_2", 7, "cola"], ["product1", 4, "hamburger"]] This is what I am aiming for: ...

Is it considered secure to encase a function within jQuery's removeClass()?

I'm currently developing a unique slider that includes a dynamic video element. With each slide transition, a new video is added to the DOM while the previous one is removed. To achieve this effect, I am utilizing CSS transitions along with a specific ...

Where should I place my elements to ensure proper positioning in the Code Generator?

Hey everyone, I've been working on developing a code generator similar to Sketch2Code and I've hit a roadblock with my JSON structure. I'm trying to create an HTML page using the myData example provided with a predefined HTML structure. Thin ...

What is the reason for substituting a reference to an object with its actual value?

I am utilizing node.js and express. Within the 'req.session', I have stored a complex object containing an array of objects. Additionally, I store a reference to one of the objects in the array. For example: var value = { name: "name" , ...

"Troubleshooting: State array in ReactJS/NextJS not rendering correctly following setState

I am facing challenges with rendering my objects using .map() within React / NextJS. Within my code, I have a function where I retrieve images from Firebase Cloud Storage as shown below: getImages = () => { let firebase = loadFirebase() ...

Is JSONP necessary for accessing the API subdomain?

Currently in the process of setting up an application with the API being hosted at http://api.project.com while the main app will reside at https://app.project.com. This app is going to be entirely based on angular.js. I'm curious if JSONP is the onl ...

Identify duplicate values in an array by comparing pairs of elements

If the array contains the data shown below: let array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 }, { name: "Suresh", SalseVersion: 12, MarketingCode: 13 }, { name: "Siva", SalseVersion: 10, MarketingCode: 14 }, { na ...

When an array is passed into a Vuex action function, it transforms into something other than just

EDIT: Added extra code in the filterEvents snippet for more context. I'm struggling to understand the behavior of my code. My goal is to pass an array into an action function within my Vuex store. However, when I return a Promise inside that action f ...

Keep scrolling until Python elements are discovered

My goal is to create a Facebook script that can automatically add all friends from my "Friend List" who are not already on my friend's list. However, the issue arises when there are mutual friends at the top of the list. I need the script to scroll do ...

Retrieving JavaScript values using Selenium

I am trying to retrieve these JavaScript values from a web application. var contestPlayResponse = { "winningPrizeIndex" : 1, "playMode" : "NORMAL", "playerId" : "abc123", "gameVersion" : "0-1-86", "gameId" : "blue250k ...