一点正则表达式应该可以解决问题(更新,见下文):
$(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/