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



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

我已经能够使用regex提取所有图像元素,并且对于每个识别的图像元素,我可以解析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[wW]+?/?>/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=["']?((?:.(?!1|>))*.?)"([^"]*).*name=["']?((?:.(?!1|>))*.?)"([^"]*)/
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);

最新更新