skip to Main Content

I currently have the following under a to generate blocks of Divs based on 2 remote consts:

const images = ["images/1.png", "images/2.png", "images/3.png",];

const text = ["txt1", "txt2","txt3", "txt4"]

var target = document.querySelector(".image-grid");

var template = "<div><label class="image-container"><img src="~id~"</label><div class="share-tray"><a href="https://twitter.com/intent/tweet?text=~txtid~"><i class="fab fa-twitter"></i></a></div></div>";

images.forEach(function(item) {
        target.insertAdjacentHTML("beforeend", template.replace(/~id~/g, item));

This is working fine to place the image containers and images.
I want to be able to replace the ~txtid~ inside the template with text[i] (effectively) but a second replace doesn’t seem to work. I can’t really edit the consts as they serve other pages

Many thanks

2

Answers


  1. Chosen as BEST ANSWER
    images.forEach(function(item) {
    replacedHTML = template.replace(/~txtid~/g, text[i]);
    target.insertAdjacentHTML("beforeend", replacedHTML.replace(/~id~/g, item));
    i = i + 1
    

  2. Change the regular expression to match either ~id~ or ~txtid~, then use a replacer function to determine which was matched, and then use either the image or the text (using the iteration index).

    You could also consider using a template literal instead of " for all your "s.

    const images = ["images/1.png", "images/2.png", "images/3.png", ];
    const text = ["txt1", "txt2", "txt3", "txt4"]
    
    const target = document.querySelector(".image-grid");
    const template = `<div><label class="image-container"><img src="~id~"</label><div class="share-tray"><a href="https://twitter.com/intent/tweet?text=~txtid~"><i class="fab fa-twitter"></i></a></div></div>`;
    
    images.forEach((image, i) => {
      target.insertAdjacentHTML(
        "beforeend",
        template.replace(/~(id|txtid)~/g, (_, match) => match === 'id' ? image : text[i])
      );
    });
    console.log(target.innerHTML);
    <div class="image-grid">
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search