You need to do this :
var txt = textDiv.replace(new RegExp(searchInput, 'gi'), function(str) {
return "<span class="highlight">" + str + "</span>"
});
or
var txt = textDiv.replace(
new RegExp(searchInput, 'gi'),
"<span class="highlight">$&</span>");
gi
->
all case insensitive matching text
$(document).ready(function() {
// globals
var searchInput;
var textDiv;
$('.searchBtn').click(function(event) {
event.preventDefault();
// set the values of the search and the text
searchInput = $('.searchInput').val();
textDiv = $('.textDiv').text();
var reg = new RegExp(searchInput, 'gi');
var txt = textDiv.replace(reg, function(str) {
return "<span class="highlight">" + str + "</span>"
});
$('.textDiv').html(txt);
});
});
.textDiv {
height: 100px;
width: 500px;
text-align: center;
padding: 20px;
margin: 0 auto;
}
.highlight {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<div class="main">
<div class="searchDiv">
<h3> Mask A Word In The Text: </h3>
<label>
<input class="searchInput" type="text" value = "iS"/> </label>
<button class="searchBtn" type="button"> Search </button>
</div>
<div class="textDiv">
Bastille Day is the common name given in English-speaking countries to the French National Day, which is celebrated on 14 July each year. In France, it is formally called La fête nationale (French pronunciation: [la fɛːt nasjɔnal]; The National Celebration) IS Is
and commonly Le quatorze juillet. (French pronunciation: [lə katɔʁz(ə) ʒɥijɛ]; the fourteenth of July).
</div>
</div>
</div>
4
solved Jquery – Find a word in a string and wrap it with tag