使用jQuery突出显示html中的文本

我希望做一些类似于这个插件的事情http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html

但我面临的问题是上面的插件不允许你突出显示html中的单词。

所以,如果你正在寻找my text

在html里面

 this is my text that needs highlighting 

你不会得到任何突出显示。

有没有办法突出显示文本而忽略其间的任何html标签?

我摆弄了一些允许HTML标签位于空白字符位置的RegEx:

 
this is my text that needs highlighting

JavaScript的:

 var src_str = $("#test").html(); var term = "my text"; term = term.replace(/(\s+)/,"(<[^>]+>)*$1(<[^>]+>)*"); var pattern = new RegExp("("+term+")", "i"); src_str = src_str.replace(pattern, "$1"); src_str = src_str.replace(/([^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"$1$2$4"); $("#test").html(src_str); 

在这里试试: http : //jsfiddle.net/UPs3V/

我想留下评论,但堆栈不允许我或我似乎无法找到它的按钮所以必须在答案中做到这一点。 脚本存在问题。 例如:在以下字符串中突出显示fox:

 

some text containing fox.

会打破img标签:

 var term = "fox"; term = term.replace(/(\s+)/,"(<[^>]+>)*$1(<[^>]+>)*"); var pattern = new RegExp("("+term+")", "i"); src_str ='' +'

some text containing fox.

' src_str = src_str.replace(pattern, "$1"); src_str = src_str.replace(/([^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"$1$2$4"); src_str

我正在研究一个突出显示脚本,并解决了没有意识到脚本可能必须突出显示多个标签的问题。 以下是我如何通过尝试突出显示标记内容来销毁标记,此脚本也突出显示内容中的多个实例,但不突出显示多个标记:

 str='' +'

some text containing fox. And onother fox.

' 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,"$1"); })

不确定如何组合这些脚本并使多个标签上的突出显示工作,但将密切关注此线程。

我尝试了接受的解决方案,它似乎打破了复杂的页面,如这一个(无限递归)。 另外,我并没有真正看到依赖jQuery的好处,所以我重写了代码以独立于jQuery(它也大大缩短并且不支持花哨的选项)。

如果你愿意,可以很容易地重新添加选项并使用类。

 function highlight(re, node, depth, maxdepth){ node = node || document.body; depth = depth || 0; maxdepth = maxdepth || 10; if( node.nodeType === 3 ){ var match = node.data.match(re); if(match){ var span = document.createElement('span'); span.style.backgroundColor = '#ffa'; var wordNode = node.splitText(match.index); wordNode.splitText(match[0].length); var wordClone = wordNode.cloneNode(true); span.appendChild(wordClone); wordNode.parentNode.replaceChild(span, wordNode); return 1; } } else if( depth === maxdepth ){ console.log( 'Reached max recursion depth!', node ); } else if( (node.nodeType === 1 && node.childNodes) && !/(script|style)/i.test(node.tagName) ) { for( var i = 0; i < node.childNodes.length; i++ ){ i += highlight(re, node.childNodes[i], depth + 1, maxdepth); } } return 0; }