Highlight text
by M Shameer
HTML
<script src="https://code.jquery.com"></script>
<script src="https://cdnjs.cloudflare.com"></script>
<input type="text" id="search-input" placeholder="Enter word to highlight">
<button id="search">Search</button>
<div class="container">
<div id="backdrop" class="backdrop">
<div id="highlights" class="highlights"></div>
</div>
<textarea id="myTextarea"></textarea>
</div>
CSS
.container { position: relative; width: 400px; height: 200px; }
#myTextarea, .highlights {
margin: 0;
width: 100%;
height: 100%;
font-family: sans-serif;
font-size: 16px;
line-height: 20px;
padding: 10px;
box-sizing: border-box;
white-space: pre-wrap;
word-wrap: break-word;
}
#myTextarea {
position: absolute;
top: 0; left: 0;
background-color: transparent; /* Makes text below visible */
color: #444;
z-index: 2;
}
.highlights {
color: transparent; /* Hides duplicate text, shows highlights */
z-index: 1;
}
.highlight { background-color: yellow; }
JavaScript
$(document).ready(function() {
$("#search").on("click", function() {
var inputWords = $("#search-input").val()
var wordsArray = inputWords.split(';').map(w => w.trim()).filter(Boolean);
var regex = new RegExp("(" + wordsArray.join('|') + ")", "gi");
var text = $( '#myTextarea' ).val()
var highlightedText = text.replace(regex, "<span class='highlight'>$1</span>");
$('#highlights').html(highlightedText);
// $('#myTextarea').on('keyup', function() {
// var text = $(this).val();
// console.log( text )
// // Replace words with highlighted spans
// var highlightedText = text.replace(regex, "<span class='highlight'>$1</span>");
// // Update the backdrop div
// $('#highlights').html(highlightedText);
// });
});
});