Replace Img Elements Src Attribute In Regex
Solution 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.
Solution 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);
});
Solution 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');
}
}
Solution 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");
Solution 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.
Post a Comment for "Replace Img Elements Src Attribute In Regex"