不要使用正则表达式来解析HTML。 [X] [HT] ML不是常规语言,不能可靠地使用正则表达式处理。您的浏览器内置了一个很好的HTML解析器;让它能够解决标签在哪里的问题。
此外,你也不想在身体上工作html()/innerHTML。这将对整个页面进行序列化和重新解析,这将会很慢,并且会丢失HTML中无法序列化的任何信息,例如事件处理程序,表单值和其他JavaScript引用。
下面是使用DOM的方法,似乎为我工作:
function replaceInElement(element, find, replace) {
// iterate over child nodes in reverse, as replacement may increase
// length of child node list.
for (var i= element.childNodes.length; i-->0;) {
var child= element.childNodes[i];
if (child.nodeType==1) { // ELEMENT_NODE
var tag= child.nodeName.toLowerCase();
if (tag!='style' && tag!='script') // special case, don't touch CDATA elements
replaceInElement(child, find, replace);
} else if (child.nodeType==3) { // TEXT_NODE
replaceInText(child, find, replace);
}
}
}
function replaceInText(text, find, replace) {
var match;
var matches= [];
while (match= find.exec(text.data))
matches.push(match);
for (var i= matches.length; i-->0;) {
match= matches[i];
text.splitText(match.index);
text.nextSibling.splitText(match[0].length);
text.parentNode.replaceChild(replace(match), text.nextSibling);
}
}
// keywords to match. This *must* be a 'g'lobal regexp or it'll fail bad
var find= /\b(keyword|whatever)\b/gi;
// replace matched strings with wiki links
replaceInElement(document.body, find, function(match) {
var link= document.createElement('a');
link.href= 'http://en.wikipedia.org/wiki/'+match[0];
link.appendChild(document.createTextNode(match[0]));
return link;
});