I am trying to work with the .replace function and it is working fine as long as I only have one variable to replace. As soon as I need to replace a variable more than once, it is not working anymore.
Here is part of my code:
function handleDetails(contentItem, contentKeys, templateKey, contentElementKey, callback=null) {
let contentTemplate = $('#' + templateKey).html();
for (const item of contentKeys) {
contentTemplate = contentTemplate.replace('{{' + item + '}}', contentItem[item]);
}
$(contentElementKey).append(contentTemplate);
if (callback) {
callback(contentItem);
}
}
Example: {{date}} -> replaced with 04/11/2021
Now I want to use {{date}} twice in my template but only my first {{date}} gets replaced. Therefore I tried to use /g but without success. Here is what I´ve tried so far:
contentTemplate = contentTemplate.replace('{{' + item + '}}/g', contentItem[item]);
or
contentTemplate = contentTemplate.replace('/{{' + item + '}}/g', contentItem[item]);
or
contentTemplate = contentTemplate.replace(/'{{' + item + '}}'/g, contentItem[item]);
I can´t find the right syntax. What am I doing wrong? Isn´t that the way it should work? I really appreciate any help.
Thanks in advance, Chris