
Untitled
By: a guest on
Jul 4th, 2012 | syntax:
None | size: 1.17 KB | hits: 9 | expires: Never
make keyword into link automatically, globally
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>");
}
<span>
An apple a day, makes 7 apples a week!
</span>
(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);
$("body").replacetext(/apple/gi, "<a href='http://www.$&.com'>$&</a>");