There are two parts to this. The first is the extraction of the URLs from the text, which is a tricky issue I'm not that interested in. I would do some research before using this in production. For now, I'll use an extremely simple illustrative regex.
The second part is the code for doing the replacement within text nodes. I answered a related question the other day with some reusable code and now I'm getting to reuse it. Yay.
function createImage(matchedTextNode) {
var el = document.createElement("img");
el.src = matchedTextNode.data;
el.width = 30;
el.height = 20;
return el;
}
function surroundInElement(el, regex, surrounderCreateFunc) {
var child = el.lastChild;
while (child) {
if (child.nodeType == 1) {
surroundInElement(child, regex, createImage);
} else if (child.nodeType == 3) {
surroundMatchingText(child, regex, surrounderCreateFunc);
}
child = child.previousSibling;
}
}
function surroundMatchingText(textNode, regex, surrounderCreateFunc) {
var parent = textNode.parentNode;
var result, surroundingNode, matchedTextNode, matchLength, matchedText;
while ( textNode && (result = regex.exec(textNode.data)) ) {
matchedTextNode = textNode.splitText(result.index);
matchedText = result[0];
matchLength = matchedText.length;
textNode = (matchedTextNode.length > matchLength) ?
matchedTextNode.splitText(matchLength) : null;
surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true));
parent.insertBefore(surroundingNode, matchedTextNode);
parent.removeChild(matchedTextNode);
}
}
var urlRegex = /http(s?):\/\/($|[^ ]+)/;
function replaceImageUrls(el) {
surroundInElement(el, urlRegex, createImage);
}
<div id="s">One
http://www.google.co.uk/images/logos/ps_logo2.png
two
http://www.google.co.uk/images/logos/ps_logo2.png three</div>
<input type="button" onclick="replaceImageUrls(document.getElementById('s'))" value="replace">