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.
// returns a string function sanitizeURL(string){ // removes the slash at the end of the URL if(string.charAt(string.length-1) == "/"){ return string = string.substr(0,string.length-1); } } // takes the string of the HTML and the array of links in this HTML // returns a string function urlsToAnchors(domElement){ // in the string we find the urls matched // we put these urls in an array string = domElement.innerHTML; // console.log(string) array = domElement.getElementsByTagName("a"); stringsArray = string.match(/(([A-Za-z]{3,9}):\/\/([-;:&=\+\$,\w]+@{1})?([-A-Za-z0-9\.]+)+:?(\d+)?((\/[-\+~%\/\.\w]+)?\??([-\+=&;%@\.\w]+)?#?([\w]+)?)?)/gi); // we then loop into this array to find and replace recursively in the string the URL by an Anchor tag containing this exact URL var j = 0; for(j; j<array.length; j++){ // loop in the array of strings var k = 0; // console.log(stringsArray.length); for(k; k<stringsArray.length; k++){ // if this item matches an item in the other array's items var url = sanitizeURL(array[j].href); if(stringsArray[k]== url){ // remove the element from the array stringsArray.splice(k,1); } } } // loop in the urls array and add the links to the HTML containing their respective url var i = 0; for(i; i<stringsArray.length; i++){ // if there is an HTTP in the URL if(stringsArray[i].match(/(http|https):\/\//)){ string = string.replace(stringsArray[i],"<a href='"+stringsArray[i]+"'>"+stringsArray[i]+"</a>"); } } // returns the HTML code to inject into the node (with the innerHTML property) return string; } window.onload = function(){ document.getElementsByTagName("p")[0].innerHTML = urlsToAnchors(document.getElementsByTagName("p")[0]); }
You need to login to post a comment.
