I have been trying to use string.replace() function but it is not working
here is what is i did;
const replaceTemplate = function (temp, product) {
let output = temp.replace(/{%PRODUCTNAME%}/g, product.productName);
console.log(product.productName);
output = temp.replace(/{%IMAGE%}/g, product.image);
output = temp.replace(/{%PRICE%}/g, product.price);
output = temp.replace(/{%FROM%}/g, product.from);
output = temp.replace(/{%NUTRIENTS%}/g, product.nutrients);
output = temp.replace(/{%QUANTITY%}/g, product.quantity);
output = temp.replace(/{%ID%}/g, product.id);
output = temp.replace(/{%DESCRIPTION%}/g, product.description);
if (!product.organic)
output = output.replace(/{%NOT-ORGANIC%}/g, "not_organic");
return output;
};
This function is supposed to replace all placeholders in template argument being passed.
const cardsHTML = dataObj
.map((el) => replaceTemplate(tempCard, el))
.join("");
This is my function call. dataObj is javascript object and tempcard is a html code template. I am reading it using
const tempCard = fs.readFileSync(`./templates/template-card.html`, "utf-8");
Placeholders in tempCard are not getting replaced at all.
>Solution :
Each of your replacements is starting from the original temp, not the result of the previous replacements. So you only get the last one. Except for the first one, they need to replace from output, not temp.
const replaceTemplate = function (temp, product) {
let output = temp.replace(/{%PRODUCTNAME%}/g, product.productName);
console.log(product.productName);
output = output.replace(/{%IMAGE%}/g, product.image);
output = output.replace(/{%PRICE%}/g, product.price);
output = output.replace(/{%FROM%}/g, product.from);
output = output.replace(/{%NUTRIENTS%}/g, product.nutrients);
output = output.replace(/{%QUANTITY%}/g, product.quantity);
output = output.replace(/{%ID%}/g, product.id);
output = output.replace(/{%DESCRIPTION%}/g, product.description);
if (!product.organic)
output = output.replace(/{%NOT-ORGANIC%}/g, "not_organic");
return output;
};