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

Viewed 78

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?

2 Answers

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.

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>'
Related