You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

autolink.js 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. (function () {
  2. var re = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-]*)?\??(?:[\-\+:=&;%@\.\w]*)#?(?:[\.\!\/\\\w]*))?)/g;
  3. function textNodesUnder(node) {
  4. var textNodes = [];
  5. if(typeof document.createTreeWalker === 'function') {
  6. // Efficient TreeWalker
  7. var currentNode, walker;
  8. walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, null, false);
  9. while(currentNode = walker.nextNode()) {
  10. textNodes.push(currentNode);
  11. }
  12. } else {
  13. // Less efficient recursive function
  14. for(node = node.firstChild; node; node = node.nextSibling) {
  15. if(node.nodeType === 3) {
  16. textNodes.push(node);
  17. } else {
  18. textNodes = textNodes.concat(textNodesUnder(node));
  19. }
  20. }
  21. }
  22. return textNodes;
  23. }
  24. function processNode(node) {
  25. re.lastIndex = 0;
  26. var results = re.exec(node.textContent);
  27. if(results !== null) {
  28. if($(node).parents().filter('code').length === 0) {
  29. $(node).replaceWith(
  30. $('<span />').html(
  31. node.nodeValue.replace(re, '<a href="$1">$1</a>')
  32. )
  33. );
  34. }
  35. }
  36. }
  37. jQuery.fn.autolink = function () {
  38. this.each(function () {
  39. textNodesUnder(this).forEach(processNode);
  40. });
  41. return this;
  42. };
  43. })();