Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>The second part is the code for doing the replacement within text nodes. I <a href="https://stackoverflow.com/questions/2798142/tag-like-autocompletion-and-caret-cursor-movement-in-contenteditable-elements/4026684#4026684">answered a related question</a> the other day with some reusable code and now I'm getting to reuse it. Yay.</p> <pre><code>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 &amp;&amp; (result = regex.exec(textNode.data)) ) { matchedTextNode = textNode.splitText(result.index); matchedText = result[0]; matchLength = matchedText.length; textNode = (matchedTextNode.length &gt; matchLength) ? matchedTextNode.splitText(matchLength) : null; surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true)); parent.insertBefore(surroundingNode, matchedTextNode); parent.removeChild(matchedTextNode); } } var urlRegex = /http(s?):\/\/($|[^\s]+)/; function replaceImageUrls(el) { surroundInElement(el, urlRegex, createImage); } &lt;div id="s"&gt;One http://www.google.co.uk/images/logos/ps_logo2.png two http://www.google.co.uk/images/logos/ps_logo2.png three&lt;/div&gt; &lt;input type="button" onclick="replaceImageUrls(document.getElementById('s'))" value="replace"&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload