简体   繁体   English

如何使用 HTML 和 Javascript 突出显示文本中的特定单词?

[英]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.我想使用 HTML 和 JS 来实现一个 function ,它可以突出显示文本中否定词词典中包含的所有单词。 Here is my JS code:这是我的 JS 代码:

    {% 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就像这张图片(“hired”、“begins”和“stumped”):在此处输入图片描述

I just want my program to highlight the whole words instead of a part of a word.我只希望我的程序突出显示整个单词而不是单词的一部分。 What should I do?我应该怎么办?

You can use您可以使用

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

Here, {{neg}} will only match if在这里, {{neg}}只会匹配

  • immediately before {{neg}} , there is either start of string or a char other than a letter, digit or underscore and紧接在{{neg}}之前,有字符串开头或除字母、数字或下划线以外的字符,并且
  • immediately after {{neg}} , there is either end of string or a char other than a letter, digit or underscore.紧接{{neg}}之后,有字符串结尾或除字母、数字或下划线以外的字符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM