Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h3>1. Here is the <a href="http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/" rel="nofollow">jQuery plugin which replaces text snippets</a></h3> <pre><code>/** * 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 &amp;&amp; /&lt;/.test( new_val ) ) { $(node).before( new_val ); remove.push( node ); } else { node.nodeValue = new_val; } } } } while ( node = node.nextSibling ); } remove.length &amp;&amp; $(remove).remove(); }); }; </code></pre> <h3>2. Here is the code which you can use to achieve the replacements</h3> <pre><code>// 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 &lt; size; i++){ // create a regex for each affiliate reg = new RegExp('('+affiliates[i][0]+')','gi'); // finally replace the string with the link // NOTE: do not forget to include the aforementioned plugin before this code, // otherwise this won't work $p.replaceText(reg, '&lt;a href="'+affiliates[i][2]+'"&gt;$1&lt;/a&gt;'); } </code></pre> <p><a href="http://jsfiddle.net/Shef/7nxv3/" rel="nofollow"><strong>Here is a demo</strong></a></p> <h3>3. You need to make some changes</h3> <p>All you have to do is change the jQuery selector, and the affiliates array. The rest will be taken care of by the plugin. <strong>The plugin is smart enough not to replace the element's attributes</strong>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload