Created
March 26, 2014 18:09
-
-
Save juanbrujo/9789622 to your computer and use it in GitHub Desktop.
Find URL's within an element and wrap them
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// THE FUNCTION | |
(function($) { | |
$.fn.findLinkMakeLink = function() { | |
// Test a text node's contents for URLs and split and rebuild it with an anchor | |
var testAndTag = function(el) { | |
// Test for URLs along whitespace and punctuation boundaries | |
var m = el.nodeValue.match(/(https?:\/\/.*?)[.!?;,]?(\s+|"|$)/); | |
// If we've found a valid URL | |
if (m) { | |
// Clone the text node to hold the "tail end" of the split node | |
var tail = $(el).clone()[0]; | |
// Substring the nodeValue attribute of the text nodes based on the match boundaries | |
el.nodeValue = el.nodeValue.substring(0, el.nodeValue.indexOf(m[1])); | |
tail.nodeValue = tail.nodeValue.substring(tail.nodeValue.indexOf(m[1]) + m[1].length); | |
// Rebuild the DOM inserting the new anchor element between the split text nodes | |
$(el).after(tail).after($("<a></a>").attr("href", m[1]).html(m[1])); | |
// Recurse on the new tail node to check for more URLs | |
testAndTag(tail); | |
} | |
return false; | |
} | |
// For each element selected by jQuery | |
this.each(function() { | |
// Select all descendant nodes of the element and pick out only text nodes | |
var textNodes = $(this).add("*", this).contents().filter(function() { | |
return this.nodeType == 3 | |
}); | |
// Take action on each text node | |
$.each(textNodes, function(i, el) { | |
testAndTag(el); | |
}); | |
}); | |
} | |
}(jQuery)); | |
// USE: | |
$(element).findLinkMakeLink(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment