Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

326
Views
Simple JS code for highlighting search text in a paragraph

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;
}
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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>

More information about $&

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!