Highlighting All Matching Words In Div From Text Input
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 ex
Solution 1:
You can pass a regular expression into replace() instead of the string, with the g modifier to make replace perform a global match.
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>"));
});
}
Solution 2:
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...
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>"));
});
}
Solution 3:
Here's a working jsfiddle for you. Basically, get the text from the div, split it on space, loop through the words and see if one matches.
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);
}
Solution 4:
Use regular expression with :
- global 'g' flag to replace all the matches
- ignore case 'i' to match all cases
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>
Post a Comment for "Highlighting All Matching Words In Div From Text Input"