A small regex should do the trick (Update, see below):
$(document).ready(function(){ var needle = 'hello'; $('p').each(function(){ var me = $(this), txt = me.html(), found = me.find(needle).length; if (found != -1) { txt = txt.replace(/(hello)(?!.*?<\/a>)/gi, '<a href="">$1</a>'); me.html(txt); } }); });
Fiddle: http://jsfiddle.net/G8rKw/
Edit: this version works better:
$(document).ready(function() { var needle = 'hello'; $('p').each(function() { var me = $(this), txt = me.html(), found = me.find(needle).length; if (found != -1) { txt = txt.replace(/(hello)(?![^(<a.*?>).]*?<\/a>)/gi, '<a href="">$1</a>'); me.html(txt); } }); });
Fiddle: http://jsfiddle.net/G8rKw/3/
Edit again: this time βhelloβ is passed as a variable to the regular expression
$(document).ready(function() { var needle = 'hello'; $('p').each(function() { var me = $(this), txt = me.html(), found = me.find(needle).length, regex = new RegExp('(' + needle + ')(?![^(<a.*?>).]*?<\/a>)','gi'); if (found != -1) { txt = txt.replace(regex, '<a href="">$1</a>'); me.html(txt); } }); });
Fiddle: http://jsfiddle.net/webrocker/MtM3s/
source share