samccone
samccone

Reputation: 10926

Replace img elements src attribute in regex

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

Upvotes: 0

Views: 3107

Answers (5)

jfriend00
jfriend00

Reputation: 708046

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.

Upvotes: 2

Elias Zamaria
Elias Zamaria

Reputation: 101183

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.

Upvotes: 0

The Mask
The Mask

Reputation: 17457

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");

Upvotes: 0

user278064
user278064

Reputation: 10180

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');
    }
}

Upvotes: 0

Alnitak
Alnitak

Reputation: 339985

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);
});

Upvotes: 1

Related Questions