2010-05-27 25 views
0

我該如何修改jquery高亮,使它找不到直接在alpha字符之前或之後出現的匹配項?換句話說,我如何防止匹配中間詞?修改jQuery突出顯示? Javascript正則表達式

/* 

highlight v3 

Highlights arbitrary terms. 

<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html> 

MIT license. 

Johann Burkard 
<http://johannburkard.de> 
<mailto:[email protected]> 

*/ 

jQuery.fn.highlight = function(pat) { 
function innerHighlight(node, pat) { 
    var skip = 0; 
    if (node.nodeType == 3) { 
    var pos = node.data.toUpperCase().indexOf(pat); 
    if (pos >= 0) { 
    var spannode = document.createElement('span'); 
    spannode.className = 'highlight'; 
    var middlebit = node.splitText(pos); 
    var endbit = middlebit.splitText(pat.length); 
    var middleclone = middlebit.cloneNode(true); 
    spannode.appendChild(middleclone); 
    middlebit.parentNode.replaceChild(spannode, middlebit); 
    skip = 1; 
    } 
    } 
    else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) { 
    for (var i = 0; i < node.childNodes.length; ++i) { 
    i += innerHighlight(node.childNodes[i], pat); 
    } 
    } 
    return skip; 
} 
return this.each(function() { 
    innerHighlight(this, pat.toUpperCase()); 
}); 
}; 

jQuery.fn.removeHighlight = function() { 
return this.find("span.highlight").each(function() { 
    this.parentNode.firstChild.nodeName; 
    with (this.parentNode) { 
    replaceChild(this.firstChild, this); 
    normalize(); 
    } 
}).end(); 
}; 

糾正我,如果我錯了,但我認爲我們專注於線:

var pos = node.data.toUpperCase().indexOf(pat); 

和:

else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) { 

回答

0

var pos = node.data.toUpperCase().indexOf(pat);

indexOf方法接受一個字符串,而不是一個正則表達式作爲它的參數。所以你不能使用它搜索整個單詞。您可以從pat構造一個正則表達式,並使用String::search()方法搜索它的整個單詞出現。

var reg:RegExp = new RegExp("\\b" + pat + "\\b"); 
var pos = node.data.toUpperCase().search(reg); 

如果你想只匹配整個單詞,用單詞邊界\b周圍的話。

/\b(script|style)\b/i 
+0

這就是我要找的......但是你確定這不是行: VAR POS = node.data.toUpperCase()的indexOf(PAT); – Matrym 2010-05-27 17:39:13

+0

@Matrym查看我的更新 – Amarghosh 2010-05-28 04:14:49