Carl Papworth Carl Papworth - 1 year ago 84
HTML Question

Ignore image tags when converting hyperlink markup with jQuery

I'm using a function to convert all hyperlinks written out in text to actual working hyperlinks. However the function also targets

<img src="http://linktoimage.jpg">
inside each
breaking them up like:

<img src="<a href="http://linktoimage.jpg">http://linktoimage.jpg</a>/>

This is the function, I tried to add a
but this didn't help, so how do I ignore all children img-tags?


jQuery(this).not('img').html( jQuery(this).html().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">$1</a> ') );

Answer Source

Use .text() to get only the text in the element p rather than .html()

   $(this).html( $(this).text().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">$1</a> ') );
<script src=""></script>
<p><img src=""/></p>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download