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
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.