0

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

Christoph C.
  • 802
  • 1
  • 20
  • 35
  • `'{{' + item + '}}/g'` this will become a string, not a regex. https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression – evolutionxbox Apr 29 '21 at 10:35
  • `replace(new RegExp("{{" + item + "}}", 'g'), contentItem[item])`. You can also use template literals but that might be confuisng because of the curly brace wrapper: `new RegExp(\`{{${item }}}\`)` – adiga Apr 29 '21 at 10:37
  • 1
    @adiga this is exactly what I was looking for. Thank you so much. Didn´t know that I needed a new RegExp. If you post your comment as an answer I will upvote it – Christoph C. Apr 29 '21 at 10:39
  • I've closed it as a duplicate. I'm not aware of the full functionality, but you can skip the `contentKeys` and the loop if all of them are in this format`{{key}}`. You can just use `contentTemplate.replace(/{{([^}]+)}}/g, (_, m) => contentItem[m])` here's a fiddle: https://jsfiddle.net/adigas/7pktn3zL/ – adiga Apr 29 '21 at 10:51

0 Answers0