Thanks for adding a link to your question, it really helped. I removed my previous intricate efforts.
var items = document.getElementsByClassName('post-list-content-element'); [].forEach.call(items, function(item){ item.innerHTML = item.innerHTML.replace( /http?:\/\/\S*?\.(jpg|png|gif)/g, '<img src=$&>'); });
Caveat: this assumes that the actual images are no longer in your post-list-content-element .
Well, here is a more universal version, which is replaced only inside text fields. I will leave you to smooth out the errors :-)
var replaceInChildTextNodes = (function(){ var eachChild, splits; eachChild = function(node, f){ var children, parent = node; children = [].slice.apply(parent.childNodes); children.forEach(function(child){ f(child, parent); eachChild(child, f); }); }; splits = function(s, regexp){ var nonmatches=[], matches=[], i=0, j=0; while((match = regexp.exec(s))){ j = match.index; nonmatches.push(s.substr(i, ji)); matches.push(match[0]); i = j + match[0].length; if(!regexp.global) break; } nonmatches.push(s.substr(i)); return {nonmatches: nonmatches, matches: matches}; }; return function(nodes, regexp, replacer){ [].forEach.call(nodes, function(node){ eachChild(node, function(childNode, parent){ var match, i=0, j=0, split, newNodes=[]; if(childNode.nodeName === '#text'){ split = splits(childNode.nodeValue, regexp); if(split.matches.length === 0) return; newNodes = []; split.nonmatches.forEach(function(text, i){ if(text !== '') newNodes.push(document.createTextNode(text)); if(split.matches[i]) newNodes.push(replacer(split.matches[i])); }); newNodes.forEach(function(newNode){ parent.insertBefore(newNode, childNode); }); parent.removeChild(childNode); } }); }); }; }());
Using:
var parents = document.getElementsByClassName('post-list-content-element'); replaceInChildTextNodes(parents, /http?:\/\/\S*?\.(jpg|png|gif)/g, function(text){ var img = document.createElement('img'); img.src = text; return img; });
String # split is not used, so you donβt have to worry about capturing groups in the regular expression, and it matches the g value.
Caution: not a cross browser.