我在 SO 上找到了一个非常好的小脚本,几乎可以满足我的要求。它将单词列表的每次出现都替换为维基百科的链接。问题是我只想链接第一次出现。
这是脚本(来自this answer):
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;
});
我一直在尝试修改它(没有成功)以使用正则表达式的 indexOf insted(来自这个答案),我认为这会比正则表达式更快:
var words = ["keyword","whatever"];
var text = "Whatever, keywords are like so, whatever... Unrelated, I now know " +
"what it's like to be a tweenage girl. Go Edward.";
var matches = []; // An empty array to store results in.
//Text converted to lower case to allow case insensitive searchable.
var lowerCaseText = text.toLowerCase();
for (var i=0;i<words.length;i++) { //Loop through the `words` array
//indexOf returns -1 if no match is found
if (lowerCaseText.indexOf(words[i]) != -1)
matches.push(words[i]); //Add to the `matches` array
}
所以我的问题是如何在不使用库的情况下将这两者结合起来以获得最有效/最快的结果?