Replace strings with links

by Shef

HTML

<p class="google">Lorem ipsum dolor sit amet, consectetur Yahoo adipiscing elit. Cras Google augue urna, dapibus vitae consequat Google ac.</p>
<p id="bing">Lorem ipsum dolor sit amet, consectetur Yahoo adipiscing elit. Cras Google augue urna, dapibus vitae consequat Google ac.</p>
<p>Lorem ipsum dolor sit amet, Bing consectetur Yahoo adipiscing elit. Cras Google augue urna, dapibus vitae consequat Google ac.</p>

CSS

.google{
    color: #666
}

#bing{
    color: #999
}

JavaScript

/**
* jQuery plugin to replace text strings
*
* Taken from @link: http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/
*/

$.fn.replaceText = function( search, replace, text_only ) {
return this.each(function(){
        var node = this.firstChild,
        val, new_val, remove = [];
        if ( node ) {
            do {
              if ( node.nodeType === 3 ) {
                val = node.nodeValue;
                new_val = val.replace( search, replace );
                if ( new_val !== val ) {
                  if ( !text_only && /</.test( new_val ) ) {
                    $(node).before( new_val );
                    remove.push( node );
                  } else {
                    node.nodeValue = new_val;
                  }
                }
              }
            } while ( node = node.nextSibling );
        }
        remove.length && $(remove).remove();
    });
};

// the array of affiliate links
var affiliates = [
        ['google', 'http://www.google.com/'],
        ['bing', 'http://www.bing.com/'],
        ['yahoo', 'http://www.yahoo.com/']
    ],
    $p = $('p'), // the selector to search text within
    i = 0, // index declared here to avoid overhead on the loop
    size = affiliates.length, // size of the affiliates array 
                              // again declared here to avoid overhead
    reg; // the regex holder variable

// loop over all the affiliates array
for(i; i < size; i++){
    // create a regex for each affiliate
    reg = new RegExp('('+affiliates[i][0]+')','gi');

    // finally replace the string with the link
    $p.replaceText(reg, '<a href="'+affiliates[i][1]+'">$1</a>');
}