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

476
Views
How to highlight specific words in a text using HTML and Javascript?

I want to use HTML and JS to implement a function that can highlight all the words which included in a negative word lexicon in a text. Here is my JS code:

    {% for neg in negative_words_list %}
    var m=document.getElementById("a")
    m.innerHTML = m.innerHTML.replace(/{{neg}}/ig,"<font color=red>$&</font>");
    {% endfor %}

But when I run the code, I found parts of some words are also highlighted, because these parts just match some negative words in the lexicon. Just like this picture ("hired", "begins", and "stumped"): enter image description here

I just want my program to highlight the whole words instead of a part of a word. What should I do?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can use

.replace(/\B{{neg}}\B/ig,"<font color=red>$&</font>")

Here, {{neg}} will only match if

  • immediately before {{neg}}, there is either start of string or a char other than a letter, digit or underscore and
  • immediately after {{neg}}, there is either end of string or a char other than a letter, digit or underscore.
about 4 years ago · Santiago Trujillo Report

0

Use this formula:

{% for neg in negative_words_list %}
var m=document.getElementById("a")
m.innerHTML = m.innerHTML.replace(new RegExp(neg, 'gi'),"<font color=red>$&</font>");
{% endfor %}

============================

var st = 'hello world aa is the ba and bb to ab'
var ar = ['aa', 'ab', 'ba', 'bb']
for (let i=0; i<ar.length; i++) {
    st = st.replace(new RegExp(ar[i], 'gi'), "<font color=red>$&</font>")
}
// output: st = 'hello world <font color=red>aa</font> is the <font color=red>ba</font> and <font color=red>bb</font> to <font color=red>ab</font>'
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!