javascript 从文本输入突出显示div中的所有匹配单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22493700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
highlighting all matching words in div from text input
提问by user2014429
I have made a function which highlights matching words in a div. but if there are two identical words separated by a different word then only the first word is highlight. so for example if the search criterion was the word "burn", and in the text was the sentence "burn baby burn", I would want it to highlight both "burn"'s. this jsFiddledemonstrates how it only highlights the first "burn". Here is the code below also. Any help much appreciated. Thanks for reading.
我制作了一个函数,可以突出显示 div 中的匹配单词。但如果有两个相同的词被不同的词隔开,那么只有第一个词是高亮显示。因此,例如,如果搜索条件是“烧伤”这个词,而文本中的句子是“烧伤婴儿烧伤”,我希望它同时突出显示“烧伤”。这个jsFiddle演示了它如何只突出显示第一个“烧伤”。这里也是下面的代码。非常感谢任何帮助。谢谢阅读。
css
css
.highlight{
font-weight:bold;
color:green;
}
html
html
<input id = "search" type ="text" value = "burn">
<div class = "searchable">burn baby burn</div>
javascript
javascript
if($('#search').val().length !== 0){
$('.searchable').each(function(){
$(this).html($(this).html().replace($('#search').val(),"<span class = 'highlight'>"+$('#search').val()+"</span>"));
});
}
回答by Danny
You can pass a regular expression into replace() instead of the string, with the g modifier to make replace perform a global match.
您可以将正则表达式传递给 replace() 而不是字符串,使用 g 修饰符使 replace 执行全局匹配。
if($('#search').val().length !== 0){
$('.searchable').each(function(){
var search_value = $("#search").val();
var search_regexp = new RegExp(search_value, "g");
$(this).html($(this).html().replace(search_regexp,"<span class = 'highlight'>"+search_value+"</span>"));
});
}
回答by Danny
Take care of regex special characters.
Maintain uppercase & lowercase.
注意正则表达式特殊字符。
保持大写和小写。
So taking care of above things with case insensitive search (in most cases, this is desired; otherwise just remove "i"), here is the final code...
因此,通过不区分大小写的搜索来处理上述事情(在大多数情况下,这是需要的;否则只需删除“i”),这是最终代码......
if ($('#search').val().length !== 0) {
$('.searchable').each(function() {
//Handle special characters used in regex
var searchregexp = new RegExp($("#search").val().replace(/[.*+?^${}()|[\]\]/g, '\$&'), "gi");
//$& will maintain uppercase and lowercase characters.
$(this).html($(this).html().replace(searchregexp, "<span class = 'highlight'>$&</span>"));
});
}
回答by Malevolence
Here's a working jsfiddlefor you. Basically, get the text from the div, split it on space, loop through the words and see if one matches.
这是一个适合您的jsfiddle。基本上,从 div 中获取文本,在空间上将其拆分,遍历单词并查看是否匹配。
var term = $('#search').val().trim().toLowerCase();
if (term.length > 0) {
var source = $('.searchable').text();
var words = source.split(' ');
var output = '';
$.each(words, function(idx, word) {
if (term === word.toLowerCase()) {
output += '<span class="highlight">' + word + '</span> ';
} else {
output += word + ' ';
}
});
$('.searchable').html(output);
}
回答by Trafalgar Law
Use regular expression with :
使用正则表达式:
- global 'g' flag to replace all the matches
- ignore case 'i' to match all cases
- 全局 'g' 标志替换所有匹配项
- 忽略 case 'i' 以匹配所有情况
Do not forget to escape special characters
不要忘记转义特殊字符
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
const SEARCH_VALUE = $("#search").val().trim();
if (SEARCH_VALUE.length > 0) {
$('.searchable').each(function() {
const DIV_TEXT_CONTENT = $('.searchable').text();
const SPLIT_CONTENT = DIV_TEXT_CONTENT.split(" ");
SPLIT_CONTENT.forEach((word, index) => {
const SEARCH_REGEXP = new RegExp(escapeRegExp(SEARCH_VALUE), "gi")
if (SEARCH_REGEXP.test(word))
$(this).html($(this).html().replace(SEARCH_REGEXP, "<span class = 'highlight'>" + word + " </span>"));
});
})
}
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\^$|#\s]/g, "\$&");
}
.highlight {
font-weight: bold;
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="search" type="text" value="BuRn">
<div class="searchable">burn baby burn</div>