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.

1 Answer 1

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>"
Sign up to request clarification or add additional context in comments.

2 Comments

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)
Edited my answer. Now the src attributes stored in an array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.