使用 RegEx 替换 html 字符串中的所有图像 src 属性

Replace all image src attributes from html string using RegEx

我有一个包含 HTML 代码的字符串,该代码可能包含多个图像。我需要从字符串中提取所有图像引用并动态替换 src 属性。

我已经能够使用正则表达式提取所有图像元素,并且对于每个已识别的图像元素,我可以解析 namesrc 属性,但我不确定如何去关于替换 src 属性,然后将其推回到原始字符串中。

// Define html string with images
const htmlString = `<p>Here's an image of people:</p><p><br></p><img class="projectImage" src="http://localhost:9199/v0/b/myApp-test.appspot.com/o/images%2Fprojects%2FbqIFfaNFV8SqO3rn0GRH%2Fdraft%2Fpeople-3137672_1920.jpeg?alt=media&amp;token=1369544e-abd0-4b53-a37a-bf325013dcb7" name="people-3137672_1920.jpeg"><p><br></p><p><br></p><p>and here's an image of some dogs:</p><p><br></p><img class="projectImage" src="http://localhost:9199/v0/b/myApp-test.appspot.com/o/images%2Fprojects%2FbqIFfaNFV8SqO3rn0GRH%2Fdraft%2Fdogs.webp?alt=media&amp;token=1c93469a-0537-4a43-9387-13f0bf8d64c9" name="dogs.webp"><p><br></p>`

// Generate list of images
const imageElements = htmlString.match(/<img[\w\W]+?\/?>/g)
console.log(`found ${imageElements.length} image element(s):`)

// For each image identify the name and src attributes
imageElements.forEach(imageElement => {
  const regex = /<img[^>]*?src=["\']?((?:.(?!|>))*.?)"([^"]*).*name=["\']?((?:.(?!|>))*.?)"([^"]*)/
  const match = regex.exec(imageElement)
  const src = match[2]
  const name = match[4]

  console.log({ name, src })
  
  // if(name === 'dogs.web') { replaceSrc('https://newLink.com) ??? }
})

如何替换 src 属性并将更新的图像组件推回原始 html 字符串(或修改后的克隆 html 字符串)?

就像@LMD 在评论中建议的那样,只需为此使用 DOM。

let el = document.createElement('div');
el.innerHTML = `<p>Here's an image of people:</p><p><br></p><img class="projectImage" src="http://localhost:9199/v0/b/myApp-test.appspot.com/o/images%2Fprojects%2FbqIFfaNFV8SqO3rn0GRH%2Fdraft%2Fpeople-3137672_1920.jpeg?alt=media&amp;token=1369544e-abd0-4b53-a37a-bf325013dcb7" name="people-3137672_1920.jpeg"><p><br></p><p><br></p><p>and here's an image of some dogs:</p><p><br></p><img class="projectImage" src="http://localhost:9199/v0/b/myApp-test.appspot.com/o/images%2Fprojects%2FbqIFfaNFV8SqO3rn0GRH%2Fdraft%2Fdogs.webp?alt=media&amp;token=1c93469a-0537-4a43-9387-13f0bf8d64c9" name="dogs.webp"><p><br></p>`

el.querySelectorAll('img').forEach((imgEl) => {
  imgEl.src = 'my.newSource.com/img/1';
});

console.log(el.innerHTML);