Replace img elements src attribute in regex

2020-05-01 07:18发布

问题:

Solved it in case anyone needs it here it is

var feed      =   feeds.entries[i].content;
var parsedFeed    =   feed.replace(/src=/gi, "tempsrc=");
var tmpHolder =   document.createElement('div');
tmpHolder.innerHTML=parsedFeed;

I have a string containing html markup which include <img src='path.jpg'/>

I would like to run a regex against the string to replace every src attr to tmpSrc

so

 <img src='path.jpg'/>

would turn into

 <img tmpSrc='path.jpg'/>

this is in javascript by the way

and here is the root issue posted in other places but has not been solved

Browser parse HTML for jQuery without loading resources

How to parse AJAX response without loading resources?

Thanks

回答1:

If this is a string you control and not HTML retrieved from a web page, then you can indeed safely use a regex. To change all occurences of <img src= to <img tmpSrc=, you can use this operation:

var str = "<img src='path.jpg'/>";   // whatever your source string is
str = str.replace(/<img src=/gi, "<img tempSrc=");

What the other posters have been saying is that regex are not good to use on HTML retrieved from a web page because different browsers return different forms of HTML so it makes it hard to reliably match it. But, if the string you're trying to do a replace on is under your own control and you can know the format of it, then this regex should work fine.



回答2:

Manipulating HTML with RegExps is error prone.

If you can suffer to include jQuery in your page:

$('img').each(function() {
    var src = this.src;
    $(this).attr('tmpSrc', src).removeAttr(src);
});


回答3:

function replace() {
    var images = document.getElementsByTagName('img'),
        srcValue,
        max
        i;

    for (i = 0, max = images.length; i < max; i++) {
       srcValue = images[i].getAttribute('src');
       images[i].setAttribute('tmpSrc', srcValue);
       images[i].removeAttribute('src');
    }
}


回答4:

as string:

input = " <img src='path.jpg'/>"; 
output = input.replace("src","tmpSrc"); 

using DOM:

    e = document.getElementById("theimg");  
    e.tmpSrc = e.src;
   e.removeAttribute("src");


回答5:

Check out this post explaining the problems with using regexes to parse HTML. It is tricky and probably not worth the effort. I don't think there is any way that is guaranteed to work.