我想在html内容中突出显示文本而不使用jquery影响样式属性。
我在div中有html内容,我想在该特定div内容中突出显示搜索关键字,但不应替换样式属性。
<div class='resume_details_list'>
<p style="margin:0pt;">
Over 7.8+ years of experience <span style="font-size:10pt;">complete development life cycle - Requirement, Program design, Coding, Testing, Deployement,Stylesheet, margin Help and Documentation with Database Structure design. Having Onsite/Offshore work experience.</span>
</p>
</div>
现在我要突出显示关键字&#34; style&#34;或&#34;保证金&#34;为此我使用下面的代码
var selector = ".resume_details_list";
var searchTerm = 'style';
var searchTermRegEx = new RegExp(searchTerm, "ig");
var matches = $(selector).text().match(searchTermRegEx);
if (matches != null && matches.length > 0) {
if (searchTerm === "&") {
searchTerm = "&";
searchTermRegEx = new RegExp(searchTerm, "ig");
}
$(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>" + searchTerm + "</span>"));
}
现在它突出了文本的任何地方&#34; style&#34;出现了,但它打破了我的HTML内容。但我不想替换样式中的样式标记或css属性。
请帮我解决问题。提前谢谢。
答案 0 :(得分:0)
您也许可以使用此正则表达式 searchTerm + '(?![=\\-;:"_\'])'
。
var selector = ".resume_details_list";
var searchTerm = 'style';
var searchTermRegEx = new RegExp(searchTerm + '(?![=\\-;:"_\'])', "ig");
var matches = $(selector).text().match(searchTermRegEx);
if (matches !== null && matches.length > 0) {
if (searchTerm === "&") {
searchTerm = "&";
searchTermRegEx = new RegExp(searchTerm, "ig");
}
$(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>" + searchTerm + "</span>"));
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='resume_details_list'>
<p style="margin:0pt;">
Over 7.8+ years of experience <span style="font-size:10pt;">complete development life cycle - Requirement, Program design, Coding, Testing, Deployement,Stylesheet, margin Help and Documentation with Database Structure design. Having Onsite/Offshore work experience.</span>
</p>
</div>
&#13;
答案 1 :(得分:0)
我已将正则表达式更改为
var searchTermRegEx = new RegExp('(?![^<]+>)' + searchTerm , 'gi');
RegEx检查不属于HTML标记的文本。它只会检查文字。它的工作正常,符合我的要求。