Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make keyword into link automatically, globally

is there a way to make a every instance of a word automatically turn into a link?

so for instance, everytime I write "apple", it is automatically formatted to <a href="www.apple.com" class="whatever" target="_blank">apple</a>

I'm assuming i could use javascript or possibly jquery.

thanks!

like image 996
Black Magic Tropical Avatar asked Jan 21 '11 01:01

Black Magic Tropical


2 Answers

very very simple example...

jQuery

var span = $('span');
    span.html(function(i,html){
        replaceTextWithHTMLLinks(html);
    }); // jQuery version 1.4.x


function replaceTextWithHTMLLinks(text) {
  var exp = /(apple)/ig;
    return text.replace(exp,"<a class='link' href='http://www.$1.com' target='_blank' >$1</a>"); 
}

html

<span> 
An apple a day, makes 7 apples a week!
</span>

demo

like image 79
Reigel Avatar answered Sep 25 '22 07:09

Reigel


Here's a simple jQuery plugin that should do the trick. It will only select text nodes so that if you have an element with a class apple or id apple it won't get replaced. Additionally, if you have a link <a href="#">apple</a> it won't get replaced (might be a little more than you need, but I thought I'd post it anyway):

(function($) {
    $.fn.replacetext = function(target, replacement) {
         // Get all text nodes:
         var $textNodes = this
                 .find("*")
                 .andSelf()
                 .contents()
                 .filter(function() {
                     return this.nodeType === 3 &&
                         !$(this).parent("a").length;
                 });

         // Iterate through the text nodes, replacing the content
         // with the link:
         $textNodes.each(function(index, element) {
             var contents = $(element).text();
             contents = contents.replace(target, replacement);
             $(element).replaceWith(contents);
         });
    };
})(jQuery);

Usage:

$("body").replacetext(/apple/gi, "<a href='http://www.$&.com'>$&</a>");

Working example: http://jsfiddle.net/andrewwhitaker/VmHjJ/

Note that this could become inefficient rather quickly due to the use of the $("*") selector. If possible, you should replace it with something more specific (or remove the .find("*").andSelf() portion entirely and pass the plugin a more specific selector).

like image 26
Andrew Whitaker Avatar answered Sep 22 '22 07:09

Andrew Whitaker