I need to write a script that reads an HTML file in which there are multiple images declared. The thing is the call to the image is simple and I need to add several instructions. From this code :
<img src="myImage1.jpg" class="image_document">
<img src="myImage2.jpg" class="image_document">
I have to get this :
<a onclick="bloquedefilementchapitres();" href="articles/myImage1.jpg" class="fancybox" rel="images"><img src="articles/myImage1.jpg" class="image_document"></a>
<a onclick="bloquedefilementchapitres();" href="articles/myImage2.jpg" class="fancybox" rel="images"><img src="articles/myImage2.jpg" class="image_document"></a>
So, I tried to use regex to perform this thinking that every image could be detected by regex. Then, every filename could be stored in an array so that I would be able to use the filename to write the link.
Here is what I did :
var recherche_images,
urls = [],
str = theHTMLcode,
rex = /<img[^>]+src="?([^"\s]+)"/g;
while (recherche_images = rex.exec(str)) {
urls.push(recherche_images[1]);
}
for (var v = 0; v < urls.length; v++) {
str = str.replace(/<img src=\"/, '<a onclick=\"bloquedefilementchapitres();\" href=\"articles/' + urls[v] + '\" class=\"fancybox\" rel=\"images-' + idunite + '\"><img src=\"articles/');
}
str = str.replace(/image_document\">/g, 'image_document\"></a>');
If the HTML document only contains one image, it works. If two images are declared, the program loops on the first image and ignores the second image.
Is there any way to tell to the replace function to start at a certain point in the string? Is there any better way to perform this?