'Iterate through an array and excecute functions in order javascript

I'm struggling trying to iterate through an array while updating some content(string). Currently, I have this code:

const replaceUrls = async (content: string) => {
  let allImgsUpdated = 0;
  let newContent = content;
  const oldImgs = content.match(/https?:\/\/.*\.(?:png|jpg|jpeg|svg|gif)/gi);
  const newImages = ["first", "second"];

  if (oldImgs) {
    oldImgs.forEach((old, idx) => {
      try {
        newContent.replace(old, newImages[idx]);
      } finally {
        allImgsUpdated++;
      }
    });
  }

  if (oldImgs && oldImgs?.length >= allImgsUpdated) return newContent;
};

My objective is to update the newContent two oldImages urls (this is a test, later I will update the images to be dynamic to how much 'oldImages' I have) to the new ones. I did the allImgsUpdated workaround so I can return the newContent when the forEach already finished



Solution 1:[1]

I solved it with this workaround:

const replaceUrls = async (content: string) => {
  let allImgsUpdated = 0;
  let newContent = content;
  const oldImgs = content.match(/https?:\/\/.*\.(?:png|jpg|jpeg|svg|gif)/gi);
  const newImages = ["primera", "segunda"];

  if (oldImgs) {
    oldImgs.forEach((old, idx) => {
      try {
        const updatedContent = newContent.replace(old, newImages[idx]);
        return (newContent = updatedContent);
      } finally {
        allImgsUpdated++;
      }
    });
  }

  if (oldImgs && oldImgs?.length >= allImgsUpdated) return newContent;
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Innk