The following regular expression replacements will replace links to <a> and image links to <img> elements. It excludes links that are already inside href=" or src=" etc.
function replaceStuff(html) { return html .replace(/[^\"]http(.*)\.(png|jpg|jpeg|gif)/g, ' <img src="http$1.$2">' .replace(/[^\"]http(.*)\.([a-zA-Z]*)/g, ' <a href="http$1.$2">http$1.$2</a>') ); }
You can call it like this:
// will replace the link to <a> replaceStuff('Hello http://google.com'); // will not replace anything replaceStuff('Hello <a href="http://google.com">ff</a>'); // will replace image link to <img> replaceStuff('Hello http://google.com/image.png'); // will not replace anything replaceStuff('Hello <img src="http://google.com/image.png">');
source share