Carl Papworth Carl Papworth - 1 month ago 5
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
<p>
breaking them up like:

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


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

js-function:

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

Answer

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

$(document).ready(function(){
$('p').each(function(){
   $(this).html( $(this).text().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">$1</a> ') );
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>http://www.google.com</p>
<p>http://www.google.com</p>
<p>http://www.google.com</p>
<p>http://www.google.com</p>
<p>http://www.google.com</p>
<p><img src="http://www.google.com"/></p>