HTML中的全文搜索忽略标记/& [英] Full text search in HTML ignoring tags / &
问题描述
我最近看到很多库在HTML页面中搜索和突出显示术语。然而,我看到的每个图书馆都有同样的问题,他们找不到部分包含在html标签中的文本,或者他们无法找到特殊字符。< / p>
示例a:
< span>这是一个测试。这是< b>测试< / b>太< /跨度>
搜索测试会找到第一个实例,而不是第二个。 b
$ b
示例b:
< ;跨度>西班牙语铅笔称为l& aacute; pices< / span>
搜寻lápices或lapices将无法产生结果。
有没有一个JS库可以做到这一点,或者至少是一种避开这些障碍的方法?
在此先感谢!
您可以使用 window.find()
在非IE浏览器和 TextRange
的 findText()
方法在IE中。以下是一个例子:
http://jsfiddle.net / xeSQb / 6 /
不幸的是,在版本15切换到Blink渲染引擎之前,Opera不支持窗口.find
或 TextRange
。如果这是您的担忧,则相当重要的替代方法是将 TextRange 和 CSS类应用程序模块的 Rangy 库,如以下演示所示: http://rangy.googlecode.com/svn/trunk/demos/textrange.html
代码:
函数doSearch(text){
if(window.find&& window.getSelection){
document.designMode =on;
var sel = window.getSelection();
sel.collapse(document.body,0); (window.find(text)){
document.execCommand(HiliteColor,false,yellow);
while
sel.collapseToEnd();
}
document.designMode =off;
} else if(document.body.createTextRange){
var textRange = document.body.createTextRange();
while(textRange.findText(text)){
textRange.execCommand(BackColor,false,yellow);
textRange.collapse(false);
}
}
}
I've recently seen a lot of libraries for searching and highlighting terms within an HTML page. However, every library I saw has the same problem, they can't find text partly encased in an html tag and/or they'd fail at finding special characters which are &-expressed.
Example a:
<span> This is a test. This is a <b>test</b> too</span>
Searching for "a test" would find the first instance but not the second.
Example b:
<span> Pencils in spanish are called lápices</span>
Searching for "lápices" or "lapices" would fail to produce a result.
Is there a JS library that does this or at least a way to circumvent these obstacles?
Thanks in Advance!
Bruno
You can use window.find()
in non-IE browsers and TextRange
's findText()
method in IE. Here's an example:
Unfortunately Opera prior to the switch to the Blink rendering engine in version 15 doesn't support either window.find
or TextRange
. If this is a concern for you, a rather heavyweight alternative is to use a combination of the TextRange and CSS class applier modules of my Rangy library, as in the following demo: http://rangy.googlecode.com/svn/trunk/demos/textrange.html
Code:
function doSearch(text) {
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.execCommand("HiliteColor", false, "yellow");
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, "yellow");
textRange.collapse(false);
}
}
}
这篇关于HTML中的全文搜索忽略标记/&的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!