I'm struggling with the logic...suppose I have this string:
var s = '<span>foo bar</span><img src="www.foo.bar"><img src="www.blah.blah">
<span>blah blah blah</span>';
What I want to do is cut out the sources of each image and reconstruct the "s" string without the image sources. Here's what I have so far but it's wrong...
numImgs = s.match(/<img/gi).length;
if (numImgs > 0) {
var imgSrc, startSrc = 0, endSrc = 0;
for (var i = 0; i < numImgs; i++) {
(function() {
startSrc = s.indexOf('<img src="', endSrc);
endSrc = s.indexOf('"', startSrc + 10);
imgSrc = s.substring(startSrc+10, endSrc);
s = s.substring(0, startSrc+10) + s.substring(endSrc, s.length);
console.log("start: " + startSrc + " end: " + endSrc + "\n" + s);
})(i);
}
}
I understand I can't use s.indexOf('<img src="', endSrc)
for the start because second time the "s" string has changed and endSrc
is way off. How can I achieve what I'm trying to do here, to get the second, third, fourth img
?
The result would be:
var s = '<span>foo bar</span><img src=""><img src=""><span>blah blah blah</span>';
SOLUTION: this is probably a very dirty way of doing this but for what I have, I added startSrc = s.indexOf('<img src="data');
so it will find the first occurrance of a src
which is not empty.