使用Javascript从列表中键入时高亮显示单词

Highlight words when typed from a list with Javascript

本文关键字:高亮 显示 单词 Javascript 列表 使用      更新时间:2023-09-26

我正在寻找一种方法来突出显示文本框中的单词(或其他标记或使单词引人注目的方法),如果它们在列表中(可能是带有Javascript的数组列表)。

我不希望这是实时的,一个检查文本框中单词的按钮会非常好地工作。基本上是一个"如果Word是(Word1、Word2等),则在此处插入更改到Word。"

我也很满意,只是把单词全大写表示变化。什么都容易。我是Javascript的新手,只了解如何做到这一点的基本概念,我想学习如何使它与文本框交互。

您可以将其加粗为<b>Word</b>,也可以根据<em>Word</em>的某些样式进行强调https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em有关em标签的更多信息。

这里有一个快速的javascript示例,用于处理gabesoft答案注释中引用的contenteditable属性。您可以定义单词列表,指定文本框,然后使用按钮进行高亮显示。

JSFiddle示例

HTML:

<p contenteditable="true">This is a test of the word highlight system.</p>
<button onClick="highlightWords()">highlight</button>

JS:

//define words you want highlighted
var arr = ['test', 'system'];
//locate the element on the page to do the word operations
//this will find the first <p> tag
var textbox = document.getElementsByTagName('p')[0];
var highlightWords = function() {
  //foreach word, perform highlighting actions
  arr.forEach(function(word) {
    //build regular expression to match against each variable (word) in our list
    var regex = new RegExp("(" + word + ")", "gi");
    //g = can find multiple instances (global)
    //i = case insenstive
    //replace predefined textbox HTML with 'highlighted' version
    //the regex will find matching words and wrap them in <strong> tags
    //the $1 represents the matched word
    textbox.innerHTML = textbox.innerHTML.replace(regex, "<strong>$1</strong>");
  });
}