少しの正規表現でうまくいくはずです(更新、以下を参照):
$(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);
}
});
});
フィドル: http://jsfiddle.net/G8rKw/
編集:このバージョンはよりうまく機能します:
$(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);
}
});
});
フィドル: http://jsfiddle.net/G8rKw/3/
もう一度編集: 今回は、「hello」が変数として正規表現に渡されます
$(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);
}
});
});
フィドル: http://jsfiddle.net/webrocker/MtM3s/