Focal55 wants to be your web guy

jQuery Tutorial: Change URLs in text into Links Automatically

June
21

By Joe Ybarra, Lead Developer

Tags: jquery

ORANGE COUNTY, Calif. -- If you need to change text URLs into HTML links automatically you can use jQuery to easily make this happen.

Use JQuery to turn text string into a anchor links automatically

First we need to use jquery to search through a chunk of text that is on our page.

<script>
$(document).ready(function(){
  //THIS JAVASCRIPT FUNCTION DOES THE WORK AND RETURNS THE
  //STRING WITH HTML ANCHOR LINKS
  function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>");
  }
  //THIS IS A JQUERY STATEMENT THAT GRABS A CHUNK OF
  //TEXT AND REPLACES IT WITH THE UPDATED STRING
  $("#content").each(function(i){
    var text = $(this).html();
    $(this).html(replaceURLWithHTMLLinks(text));
  });
});
</script>

With one JQuery statement and a nice javascript regular expression, this task is made very simple.

Add a Comment