0

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.

denikov
  • 877
  • 2
  • 17
  • 35

1 Answers1

1
var s = '<span>foo bar</span><img src="www.foo.bar"><img src="www.blah.blah"><span>blah blah blah</span>';

var srcArray = [];
var result = s.match(/(<img).+?(>)/gi);

for(var i = 0; i < result.length; i++){
    var src = result[i].match(/src=\"(.+?)\"/);
    srcArray.push(src[1]);    
}
s = s.replace(/(<img).+?(>)/gi,'<img src=""/>');
console.log(srcArray, s); //["www.foo.bar", "www.blah.blah"] "<span>foo bar</span><img src=""/><img src=""/><span>blah blah blah</span>"
alexP
  • 3,672
  • 7
  • 27
  • 36
  • That would work if I didn't need to get the image sources before...but I need them (base64 image src which need to be uploaded...big files) – denikov May 18 '15 at 14:13
  • 1
    Edited my answer. Now the src attributes stored in an array – alexP May 18 '15 at 14:28