问题描述
我正在尝试做与此插件类似的操作 http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
I am looking to do something similar to this plugin http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
但是我面临的问题是上述插件不允许您突出显示html中的单词.
But the problem I am facing is that the above plugin does not allow you to highlight words within html.
因此,如果您要查找my text
内部html之类的
this is <a href="#">my</a> text that needs highlighting
您将不会得到任何突出显示.
You will not get any highlighting.
有没有一种方法可以突出显示文本,而忽略它们之间的任何html标签?
Is there a way to highlight text while ignoring any html tags in between?
推荐答案
我摆弄了一些RegEx,它使HTML标记位于空白字符的位置:
I fiddled some RegEx which allows HTML tags at the position of whitespace chars:
<div id="test">this is <a href="#">my</a> text that needs highlighting</div>
JavaScript:
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, "<mark>$1</mark>");
src_str = src_str.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"$1</mark>$2<mark>$4");
$("#test").html(src_str);
在这里尝试: http://jsfiddle.net/UPs3V/
这篇关于使用jQuery突出显示html内的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!