I am trying to rewrite this code to suit my needs, but I am lost in all the replacing magic that the auther of the Fiddle does. Here's my modified fiddle.
My goal is to find all occurrances of "a" letter in the paragraph and highlight them. I just can't figure out why my letters are just being replaced by 1$ instead of being highlighted. Can anyone help me with this ?
HTML
<div id="searchtext">
<p>I want to highlight all "a" letters in this paragraph</p>
</div>
JS
$(document).ready(function() {
var text = 'a';
var query = new RegExp(text, "gim");
var e = document.getElementById("searchtext").innerHTML;
var enew = e.replace(/(<span>|<\/span>)/igm, "");
document.getElementById("searchtext").innerHTML = enew;
var newe = enew.replace(query, "<span>1$</span>");
document.getElementById("searchtext").innerHTML = newe;
});
CSS:
#searchtext span {
background-color: #FF9;
color: #555;
}
Use \$& instead
$(document).ready(function() {
var text = 'a';
var query = new RegExp(text, "gim");
var e = document.getElementById("searchtext").innerHTML;
var enew = e.replace(/(<span>|<\/span>)/igm, "");
document.getElementById("searchtext").innerHTML = enew;
var newe = enew.replace(query, "<span>\$&</span>");
document.getElementById("searchtext").innerHTML = newe;
});
#searchtext span {
background-color: #FF9;
color: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="searchtext">
<p>I want to highlight all "a" letters in this paragraph</p>
</div>