How to dynamically add HTML content to a JSON string with the help of Javascript

I am working with a JSON object that includes various messages to be displayed on a webpage using Javascript. This JSON file is located in a separate directory and I have full control over it, being loaded asynchronously.

There are specific cases where different messages need to be shown, some of which contain dynamic data readily available within the function. To integrate this dynamic data into the string, I currently use plus signs for concatenation.

{
  "text": {
    "successMsg": "<p class=\"success\">This is the success message. Variable is \" + dynamicData + \"<\/p> "
  }
}


//Pseudocode

function displayMsg() {
  var dynamicData = 'some data'
  if (foo) {
    //code to display the JSON text 

  }
}

However, when I attempt to showcase the message on the page, the variable is parsed as a string instead of displaying its actual value. Even though the variable holds a value at that moment, on the webpage it just shows the text dyanamicData literally.

Your assistance on this matter would be greatly valued.

Thank you

Answer №1

Insert a unique keyword into the message object, then employ the String.replaceAll() function to substitute it.

let message = {
  "text": {
    "promoMsg": '<p class="promotion">This is the promotional message. Placeholder is ##promotionalData##<\/p> '
  }
};


function showPromo(foo, promoData, message) {
  let updatedPromo = {
    ...message,
    text: { ...message.text,
      promoMsg: message.text.promoMsg.replace('##promotionalData##', promoData)
    }
  };
  if (foo) {
    console.log(updatedPromo);
  }
}

showPromo(true, 'new information', message);

If you require more flexibility, consider utilizing an object that links keywords with values and performing a regular expression substitution.

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 navigating the material ui Expanded attribute within the Expansion Panel

After looking at the image provided through this link: https://i.stack.imgur.com/kvELU.png I was faced with the task of making the expansion panel, specifically when it is active, take up 100% of its current Div space. While setting height: 100% did achi ...

Node.js route leads to a 404 error page due to a simple configuration

Trying to set up two separate routes using NodeJS with the express framework and Angular on the client side. The index page successfully renders at localhost:3000/. However, when attempting to render the login page by visiting localhost:3000/login, a GET / ...

SCRIPT5007: The property 'href' cannot be assigned a value as the object is either null or undefined

This script is functioning properly in browsers like Chrome and Firefox, however it is encountering issues when used with Internet Explorer. An error message is displayed in the IE console: SCRIPT5007: Unable to set value of the property 'href': ...

Having issues with Thymeleaf template not functioning properly when using inline JavaScript

I've encountered an issue when attempting to extract my function into a script within HTML. When written as shown below, it works perfectly: <input type="text" id="myInput" onkeypress="return confirm('Are you sure you want to delete ...

Understanding the mechanics of utilizing node modules and requiring them within an Express 4 router

After initiating a node project using an express 4 generator, I have set up the following routing code in the /routes/index.js file: // ./routes/index.js var express = require('express'); var router = express.Router(); router.get('/' ...

Fill the table with information from a JSON file by selecting options from drop-down menus

I am currently working on a web application project that involves bus timetables. My goal is to display the timetable data in a table using dropdown menus populated with JSON information. While I believe I have tackled the JSON aspect correctly, I am facin ...

hyperlink to choose a specific option from a drop-down menu

The challenge I am currently working on involves page1.html <a href="/foo"></a> foo.html <select ng-model="ctrl.listvalues"> <option id="{{item.value}}" ng-repeat="item" in ctrl.availableValues" value="{{item.value}}">item.di ...

Ajax is unintentionally duplicating the request

When the "async" parameter is set to "true", ajax sends two requests at the same time. But, when it is set to "false", there are no issues. To prevent the page from reloading, I am using the following code: $(document).ready(function() { $(document).on(& ...

Issues with loading JavaScript in Selenium

I have been trying to extract data that is loaded through google tag manager. Despite my efforts using both chrome and firefox, the li elements I need in the body always appear empty no matter what timing I use. import undetected_chromedriver as uc from ...

How to exit an ASP.NET application by pressing the exit button

I am new to asp.net and currently using Visual Studio 2012. Currently, I am working on a login page where I have two buttons: Login and Exit. Whenever I click on the Exit button, I want the application to close and also stop the debugging process. I cam ...

Naming a JSON object twice

As a newcomer to node.js, I find myself struggling with understanding the process. Can someone please guide me on where I might be going wrong? This is how I create a new Product exports.postAddProduct = (req, res, next) => { const product = new Produ ...

Vuejs Error: "No template or render function defined for a single file component"

When attempting to import all components from a folder and display one based on a passed prop, I encountered an error at runtime. I am using webpack with vue-loader to import all my components, each of which is a *.vue file. The issue arises when importi ...

What is the best way to use lodash to group objects that contain nested objects?

Currently utilizing Typescript in conjunction with Lodash! Upon retrieving data from the database, here is the resulting output: [ { "unitPrice": 0.01, "code": "92365524", "description": "Broto gr ...

Struggling to get getInitialProps working in dynamic routes with Next.js?

I am encountering an issue. The return value from the getInitialProps function is not being passed to the parent component. However, when I console.log the values inside the getInitialProps function, they appear to be correct. Here is the code snippet: i ...

Learn how to bring .Net DateTime and TimeSpan into Excel using Json and Power Query

Quick question: How can I successfully import data with .Net DateTime or TimeSpan types into Excel tables using Json and Power Query? I'm having trouble getting it to work. Here's the situation: I have sporadic data (integer values logged irregu ...

Guide: Passing and reading command line arguments in React JavaScript using npm

When launching the react application, I utilize npm start which is defined in package.json as "start": "react-scripts start -o". Within the JavaScript code, I currently have: const backendUrl = 'hardCodedUrl'; My intention ...

Is there a way to store div content in a PHP Session?

Just starting to learn php & ajax, so be patient with me. I have a clickable map. When the user clicks on a point, the value is displayed in a div. Once they select a point, they should be able to proceed to the next step. Now I want to save the content ...

"Trouble With JSON and ASP.NET WebMethod: Server-Side Method Not Executing

I am attempting to send parameters to my code behind using the WebMethod. Although I am successfully reaching the end of ajax, the method in my aspx.cs code behind is not being called and I am encountering an error. Operation failed! Details: '[ob ...

Is there a more efficient method to gather properties from an object into separate arrays without the need for using `map` twice?

Currently, my code block looks like this: res.json({ dates: rows.map(function (item) { return item.Date }), counts: rows.map(function (item) { return item.NewMembers }) }); While functional, I can't help but feel it is inefficient as the row ...

Utilizing jQuery to generate dynamic nested divs within the ul li tags

I am looking to dynamically generate nested divs within a ul li. The goal is to create the following structure programmatically: <ul> <li> <div class="videoThumbnail"> <img src="./img6.jpg" /> &l ...