-2

I want to replace src of 1st img tag with index 0 of attachments array, 2nd tag with index 1 so on and so forth without using jQuery. The html in stored inside a variable.

var body="<div dir="ltr">
             text above image
             <div>
               <img src="cid:ii_ksc42giw0" alt="IMG_20210814_124816.jpg" width="407" 
                  height="542"><br>
               <img src="cid:ii_ksc41siq0" alt="IMG_20210814_124816.jpg" width="407" 
                  height="542"><br>
             </div>
             <div>
               text below image
             </div>
          </div>"

var attachments = ['https://some-random-url-1', 'https://some-random-url-2']

1 Answers1

1

Using regular expressions to try to handle HTML is error-prone. Instead, use a parser. You seem to be doing this in a browser, so you can use DOMParser:

const doc = new DOMParser().parseFromString(body, "text/html");
const images = doc.querySelectorAll("img");
for (let i = 0, len = Math.min(attachments.length, images.length); i < len; ++i) {
    images[i].src = attachments[i];
}

Live Example:

var body=`<div dir="ltr">
             text above image
             <div>
               <img src="cid:ii_ksc42giw0" alt="IMG_20210814_124816.jpg" width="407" 
                  height="542"><br>
               <img src="cid:ii_ksc41siq0" alt="IMG_20210814_124816.jpg" width="407" 
                  height="542"><br>
             </div>
             <div>
               text below image
             </div>
          </div>`;

var attachments = ['https://some-random-url-1', 'https://some-random-url-2'];

const doc = new DOMParser().parseFromString(body, "text/html");
const images = doc.querySelectorAll("img");
for (let i = 0, len = Math.min(attachments.length, images.length); i < len; ++i) {
    images[i].src = attachments[i];
}

// ...put `doc` in the document, or use `outerHTML` if you
// need an HTML string from the result
console.log(doc.body.innerHTML);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • FYI: `console.log(doc.body.innerHTML);` shows just the string that was parsed with the changes applied - since the original string had no html, head, body etc – Bravo Aug 16 '21 at 10:36