我试图突出显示正文中所有匹配的单词,但不突出显示任何html标记中的单词。例如,给定的关键字是'para‘。下面是这段话:
<p class="para"> Example of paragraph. Lorem ipsum dolor sit amet. </p>结果是:
<p class="para">
Example of <strong>para</strong>graph. Lorem ipsum dolor sit amet.
</p>我知道使用JavaScript的replace()可以做到这一点,但我对正则表达式知之甚少。
发布于 2012-05-24 09:35:47
演示:http://jsfiddle.net/crgTU/7/
highlightWord(document.body,'para');
function highlightWord(root,word){
textNodesUnder(root).forEach(highlightWords);
function textNodesUnder(root){
var n,a=[],w=document.createTreeWalker(root,NodeFilter.SHOW_TEXT,null,false);
while(n=w.nextNode()) a.push(n);
return a;
}
function highlightWords(n){
for (var i; (i=n.nodeValue.indexOf(word,i)) > -1; n=after){
var after = n.splitText(i+word.length);
var highlighted = n.splitText(i);
var span = document.createElement('span');
span.className = 'highlighted';
span.appendChild(highlighted);
after.parentNode.insertBefore(span,after);
}
}
}
您还可以考虑调用类似于…的代码
function removeHighlights(root){
[].forEach.call(root.querySelectorAll('span.highlighted'),function(el){
el.parentNode.replaceChild(el.firstChild,el);
});
}…在你找到新的高光之前(从DOM中删除旧的高光)。
发布于 2016-01-19 23:31:13
为什么使用自制的突出显示功能是个坏主意
为什么从头开始构建你自己的高亮功能可能不是一个好主意,因为你肯定会遇到别人已经解决的问题。挑战:
例如,如果你想移除高亮显示的元素,你需要移除带有元素的文本节点,以突出显示匹配的内容,而不会破坏DOM事件并一次又一次地触发DOM重新生成(例如,对于
听起来很复杂?如果你想要一些功能,比如忽略高亮显示中的一些元素,发音符号映射,同义词映射,在iframe中搜索,分词搜索等,这会变得越来越复杂。
使用现有插件
当使用现有的、实现良好的插件时,您不必担心上面提到的事情。Sitepoint上的文章比较了流行的荧光笔插件。
看一看mark.js
mark.js就是这样一个用纯JavaScript编写的插件,但也可以作为jQuery插件使用。它的开发目的是提供比其他插件更多的机会,并提供以下选项:
<代码>H123映射自定义synonyms
或者,您可以查看this fiddle。
用法示例
// Highlight "keyword" in the specified context
$(".context").mark("keyword");
// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);它是在GitHub (project reference)上免费开发的开源软件。
发布于 2012-10-19 16:08:19
您可以使用regexp方法,但它还不会在多个标记上突出显示。例如,我的高亮显示文字“我的高亮显示”将不会高亮显示。
代码如下:
str='<img src="brown fox.jpg" title="The brown fox" />'
+'<p>some text containing fox. And onother fox.</p>'
var word="fox";
word="(\\b"+
word.replace(/([{}()[\]\\.?*+^$|=!:~-])/g, "\\$1")
+ "\\b)";
var r = new RegExp(word,"igm")
str.replace(/(>[^<]+)/igm,function(a){
return a.replace(r,"<span class='hl'>$1</span>");
})https://stackoverflow.com/questions/10729983
复制相似问题