Abhishek B.
Abhishek B.

Reputation: 5202

Make a hyper link on Html link with Jquery

I have Html contents like

<span> 
 http://j.mp/eUcRNK
</span>

I want to hyperlink on above html text like this

<span>
    <a href="http://j.mp/eUcRNK" class="link" target="_blank">
    http://j.mp/eUcRNK
    </a>
</span>

How I can do that..

Upvotes: 0

Views: 218

Answers (2)

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

$('span').html(function(i,txt){
   return $('<a>').text(txt).attr({'target':'_blank', 'href': txt }).addClass('link');
});

demo

based on the comments below, I guess this solves it.

$('span').html(function(i,txt){
   return replaceURLWithHTMLLinks(txt);
});

function replaceURLWithHTMLLinks(text) {
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(exp,"<a class='link' href='$1' target='_blank' >$1</a>"); 
}

updated fiddle

for jquery 1.3.2, just change the jQuery codes a bit.

var span = $('span');
span.html(replaceURLWithHTMLLinks(span.html()));

another updated fiddle

Upvotes: 2

rahul
rahul

Reputation: 187040

Try

$("span").each(function(){
    var text = $(this).text();
    $(this).contents().wrap("<a class='link' href='" + text + "' target='_blank' />")
});

Upvotes: 1

Related Questions