jQuery Text links to Hyperlinks
This function find all strings containing http and transforms them into real links.
by Jose SAYAGO
HTML
<div id="#feed">
<div class="content">
<p>Hey visit us at http://www.laelitenetwork.com</p>
</div>
<div class="content">
<p>Check out http://8elite.com and follow us</p>
</div>
<div class="nolink">
<p>Look ma! no links http://en.8elite.com</p>
</div>
</div>
CSS
.content, .nolink {
border: 1px dotted #cecece;
padding: 3px;
margin: 4px;
color: #333;
}
.content a {
color: #ff0000;
text-decoration: none;
border-bottom: 1px dotted #000;
}
.content a:hover { color: #ff00ff; }
JavaScript
// Check the main container is ready
$('#feed').ready(function(){
// Get each div
$('.content').each(function(){
// Get the content
var str = $(this).html();
// Set the regex string
var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig
// Replace plain text links by hyperlinks
var replaced_text = str.replace(regex, "<a href='$1' target='_blank'>$1</a>");
// Echo link
$(this).html(replaced_text);
});
});