I want to convert certain key words into affiliate links on my website. I do not want to hand-code each one of those links in every page. So I'm looking for a Javascript/Jquery based solution where using a given a list of keywords and corresponding URLs (a two dimensional array), on page load, these keywords are 'URLified' using their corresponding URLS.
I found this comment Find text string using jQuery? which has the code for a case insensitive search, but it URLifies the whole text node instead of just the word.
I could use something like the code below. But the problem is that it will URLify keywords inside <pre>
elements too. I want them URLified inside just <p>
elements.
<script type="text/javascript">
(function($) {
var thePage = $("body");
thePage.html(thePage.html().replace(/testing/ig, '<a href="http://testing.com">testing</a>'));
})(jQuery)
</script>
For eg:
<p>I'm going to test urlification</p>
<pre>
function test() {
alert(' test ');
}
</pre>
should change to
<p>I'm going to <a href="test123.com">test</a> urlification</p>
<pre>
function test() {
alert(' test ');
}
</pre>
/**
* 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
// NOTE: do not forget to include the aforementioned plugin before this code,
// otherwise this won't work
$p.replaceText(reg, '<a href="'+affiliates[i][2]+'">$1</a>');
}
All you have to do is change the jQuery selector, and the affiliates array. The rest will be taken care of by the plugin. The plugin is smart enough not to replace the element's attributes.