将字符串中找到的单词替换为大小写敏感(搜索和高亮显示)
Replacing a found word within the string to case (in)sensitive (search and highlight)
我已经采取了别人的荧光笔代码,我正试图修改它,使其为我的项目工作。总的来说,代码工作得很好,但是在显示结果方面有一个小问题。高亮笔查找指定的单词并将元素中的整个文本替换为指定的关键字。
所以在这个例子中,如果我想在句子"cat is an awesome pet"中突出一个单词"cat",我得到的结果是"cat is an awesome pet"。总是使用大写很容易,但这样做的问题是所需的单词可能在句子中的不同位置。例如:我爱我的猫。
我想做的是让脚本记住之前的区分大小写的状态,在高亮显示它之后,我想让它显示之前指定的大写或小写。
我在表函数中搜索关键字,找到关键字后应该突出显示它。
// highlighter func
function highlight_words(word, element) {
if(word){
var textNodes;
word = word.replace(/'W/g, '');
var str = word.split(" ");
$(str).each(function(){
var term = this;
var textNodes = $(element).contents().filter(function(){ return this.nodeType === 3 });
textNodes.each(function() {
var content = $(this).text();
var regex = new RegExp(term, "gi");
content = content.replace(regex, '<span class="highlight">' + term + '</span>');
$(this).replaceWith(content);
});
});
}
}
如何触发函数
//search_inp is the keyword entered in the text input field such as "Cat"
highlight_words(search_inp, $("#FoundElem table tbody .perm-name a"));
显示什么
<div id="FoundElem">
<table cellspacing="1" class="perm-table" id="table0000">
<tbody><tr class="row4" id="temp0">
<td class="perm-name"><a title=""><span class="highlight">cat</span> is an awesome pet</a></td>
</tr></tbody>
</table>
</div>
我能够做到这一点的方式是通过添加CSS大写到所有的关键字。它适用于我的情况,但对于您想要保留前一个值的情况,它将不起作用。
无论如何,这是一个css,最终帮助我。
.highlight {
background-color:yellow;
text-transform:capitalize;
}
相关文章:
- JavaScript Regex(?i)选项中字符串大小写不敏感的部分不起作用
- 使搜索不区分大小写
- 如何使用jQuery进行不区分大小写的搜索
- 正则表达式匹配整个字符串,但大小写不敏感
- 如何避免大小写敏感的返回
- 如何解决区分大小写搜索的搜索输入问题
- 用于Cordova应用程序的Javascript SQLite-使用参数搜索,其中字符串包含子字符串大小写insenst
- 在DOM中搜索字符串时不区分大小写
- 不区分大小写的自动完成搜索(使用java、javascript、jquery)
- 如何将不区分大小写添加到照片库搜索框jquery
- 使搜索文本框输入值不区分大小写
- 通过jquery搜索列表(不区分大小写)
- 如何在 JavaScript 中搜索其他不区分大小写的对象?像 _.where() 只有不区分大小写
- 使用 javascript 从 Parse 中搜索不区分大小写的数据
- 不区分大小写的字符串搜索不起作用
- 如何检查特定字符串是否存在于变量中,在javascript中具有大小写敏感和特殊字符
- 简单的大小写不敏感的搜索框的一个表与jQuery
- 将字符串中找到的单词替换为大小写敏感(搜索和高亮显示)
- 非大小写敏感的查询与TaffyDB(或其他JS数据库)
- CodeMirror自动完成:大小写敏感搜索