We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

juliend2 on 05/24/08


Tagged

regex javascript


Versions (?)


urlsToAnchors


Published in: JavaScript 


To use this snippet, you have to pass a DOM element to the urlsToAnchors function. This function then returns a string of the new generated HTML. This html contains the links for the urls that were in text.

  1. // returns a string
  2. function sanitizeURL(string){
  3. // removes the slash at the end of the URL
  4. if(string.charAt(string.length-1) == "/"){
  5. return string = string.substr(0,string.length-1);
  6. }
  7. }
  8.  
  9. // takes the string of the HTML and the array of links in this HTML
  10. // returns a string
  11. function urlsToAnchors(domElement){
  12. // in the string we find the urls matched
  13. // we put these urls in an array
  14. string = domElement.innerHTML;
  15. // console.log(string)
  16. array = domElement.getElementsByTagName("a");
  17. stringsArray = string.match(/(([A-Za-z]{3,9}):\/\/([-;:&=\+\$,\w]+@{1})?([-A-Za-z0-9\.]+)+:?(\d+)?((\/[-\+~%\/\.\w]+)?\??([-\+=&;%@\.\w]+)?#?([\w]+)?)?)/gi);
  18. // we then loop into this array to find and replace recursively in the string the URL by an Anchor tag containing this exact URL
  19. var j = 0;
  20. for(j; j<array.length; j++){
  21. // loop in the array of strings
  22. var k = 0;
  23. // console.log(stringsArray.length);
  24. for(k; k<stringsArray.length; k++){
  25. // if this item matches an item in the other array's items
  26. var url = sanitizeURL(array[j].href);
  27. if(stringsArray[k]== url){
  28. // remove the element from the array
  29. stringsArray.splice(k,1);
  30. }
  31. }
  32. }
  33. // loop in the urls array and add the links to the HTML containing their respective url
  34. var i = 0;
  35. for(i; i<stringsArray.length; i++){
  36. // if there is an HTTP in the URL
  37. if(stringsArray[i].match(/(http|https):\/\//)){
  38. string = string.replace(stringsArray[i],"<a href='"+stringsArray[i]+"'>"+stringsArray[i]+"</a>");
  39. }
  40. }
  41.  
  42. // returns the HTML code to inject into the node (with the innerHTML property)
  43. return string;
  44. }
  45.  
  46. window.onload = function(){
  47. document.getElementsByTagName("p")[0].innerHTML = urlsToAnchors(document.getElementsByTagName("p")[0]);
  48. }

Report this snippet 

You need to login to post a comment.