Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 4th, 2012  |  syntax: None  |  size: 1.17 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. make keyword into link automatically, globally
  2. var span = $('span');
  3.     span.html(function(i,html){
  4.         replaceTextWithHTMLLinks(html);
  5.     }); // jQuery version 1.4.x
  6.  
  7.  
  8. function replaceTextWithHTMLLinks(text) {
  9.   var exp = /(apple)/ig;
  10.     return text.replace(exp,"<a class='link' href='http://www.$1.com' target='_blank' >$1</a>");
  11. }
  12.        
  13. <span>
  14. An apple a day, makes 7 apples a week!
  15. </span>
  16.        
  17. (function($) {
  18.     $.fn.replacetext = function(target, replacement) {
  19.          // Get all text nodes:
  20.          var $textNodes = this
  21.                  .find("*")
  22.                  .andSelf()
  23.                  .contents()
  24.                  .filter(function() {
  25.                      return this.nodeType === 3 &&
  26.                          !$(this).parent("a").length;
  27.                  });
  28.  
  29.          // Iterate through the text nodes, replacing the content
  30.          // with the link:
  31.          $textNodes.each(function(index, element) {
  32.              var contents = $(element).text();
  33.              contents = contents.replace(target, replacement);
  34.              $(element).replaceWith(contents);
  35.          });
  36.     };
  37. })(jQuery);
  38.        
  39. $("body").replacetext(/apple/gi, "<a href='http://www.$&.com'>$&</a>");