首先,这确实应该在服务器上完成,在客户端上执行效率非常低,而且更容易出错。不过话说回来……
您可以尝试处理元素的 innerHTML,但 javascript 和正则表达式在这方面确实很糟糕。
最好的方法是使用 DOM 方法并解析每个元素的文本。当找到匹配的单词时,将其替换为 abbr 元素。这要求在文本节点中找到匹配项时,替换整个节点,因为一个文本节点现在将是 abbr 元素两侧的两个(或更多)文本节点。
这是一个简单的函数,但它可能存在您需要解决的弱点。它适用于简单的文本字符串,但您需要在更复杂的字符串上对其进行彻底测试。自然,它应该只在特定节点上运行一次,否则缩写将被双重包装。
var addAbbrHelp = (function() {
var abbrs = {
'WHO': 'World Health Organisation',
'NATO': 'North Atlantic Treaty Organisation'
};
return function(el) {
var node, nodes = el.childNodes;
var word, words;
var adding, text, frag;
var abbr, oAbbr = document.createElement('abbr');
var frag, oFrag = document.createDocumentFragment()
for (var i=0, iLen=nodes.length; i<iLen; i++) {
node = nodes[i];
if (node.nodeType == 3) { // if text node
words = node.data.split(/\b/);
adding = false;
text = '';
frag = oFrag.cloneNode(false);
for (var j=0, jLen=words.length; j<jLen; j++) {
word = words[j];
if (word in abbrs) {
adding = true;
// Add the text gathered so far
frag.appendChild(document.createTextNode(text));
text = '';
// Add the wrapped word
abbr = oAbbr.cloneNode(false);
abbr.title = abbrs[word];
abbr.appendChild(document.createTextNode(word));
frag.appendChild(abbr);
// Otherwise collect the words processed so far
} else {
text += word;
}
}
// If found some abbrs, replace the text
// Otherwise, do nothing
if (adding) {
frag.appendChild(document.createTextNode(text));
node.parentNode.replaceChild(frag, node);
}
// If found another element, add abbreviation help
// to its content too
} else if (node.nodeType == 1) {
addAbbrHelp(node);
}
}
}
}());
对于标记:
<div id="d0">
<p>This is the WHO and NATO string.</p>
<p>Some non-NATO forces were involved.</p>
</div>
并调用:
addAbbrHelp(document.getElementById('d0'));
导致(我的格式):
<div id="d0">
<p>This is the<abbr title="World Health Organisation">WHO</abbr>
and <abbr title="North Atlantic Treaty Organisation">NATO</abbr>
string.</p>
<p>Some non-<abbr title="North Atlantic Treaty Organisation">NATO</abbr> forces were involved.</p>
</div>
使用分词模式来拆分单词很有趣,因为在像“with non-NATO force”这样的字符串中,NATO 这个词仍然会被包裹,但“non-”部分不会。但是,如果缩写在文本节点或连字符之间分割,除非在 abbrs 对象中包含相同的模式作为属性名称,否则将无法识别它。