如何更改字符串中多个特定单词的颜色?

How can I change the color of multiple specific words in a string?

提问人:cerdessius 提问时间:11/15/2023 最后编辑:tacoshycerdessius 更新时间:11/15/2023 访问量:69

问:

我正在尝试创建一个函数,该函数可以读取大量文本,自动检测关键字,然后更改这些单个单词的颜色。例如,在句子“he walked to the store and then he walk to his house”中,我希望该函数能够单独检测单词“he”并将文本颜色更改为绿色,同时还检测单词“walked”以将文本颜色更改为红色,而不改变句子的其余部分。这将在更大的范围内使用更多的关键字和颜色。

我已经到了可以让我的程序检测用 or 编写的文本字符串中的某些单词的地步,但是当我尝试通过那里更改单词的颜色时,它会更改字符串中所有单词的颜色(通过更改 CSS),这不是我想要的。我还让它更改了 中的单个单词,但它也更改了其他部分中的单词。

我也很难让它更改不同的关键字,例如,当它使用绿色表示“步行”时,而实际上它应该是红色。我不想手动使用每个单词,所以我想找到一种方法来自动执行此操作。

javascript html jquery , css

评论


答:

1赞 Kokila Venkatesan 11/15/2023 #1

试试这个例子。

此功能可单独检测单词“he”并将文本颜色更改为绿色,同时还可以检测单词“walked”以在不更改句子其余部分的情况下将文本颜色更改为红色。

<html lang="en">
<head>

  <title>Coloring Words</title>
  
  <!-- Include jQuery from a CDN (Content Delivery Network) -->
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  
</head>
<body>
  <div id="coloredText">he walked to the store and then he walked to his house</div>
 
</body>
</html>
.green {
  color: green;
}

.red {
  color: red;
}
$(document).ready(function() {
  var coloredText = $("#coloredText").text();
  var keywordClasses = {
    "he": "green",
    "walked": "red",
   
  };
  var words = coloredText.split(/\s+/);

 
  for (var i = 0; i < words.length; i++) {
    var word = words[i].toLowerCase(); // Convert to lowercase for case-insensitivity
    var cssClass = keywordClasses[word];
    if (cssClass) {
      words[i] = "<span class='" + cssClass + "'>" + words[i] + "</span>";
    }
  }

 
  $("#coloredText").html(words.join(' '));
});
0赞 duckstery 11/15/2023 #2

对于纯 javascript,您可以这样做

// Original string
const original = 'he walked to the store and then he walked to his house,'
// Set original string
document.querySelector("#original").innerText = original

// On form submit
document.querySelector("form").addEventListener("submit", onSubmit)
// On form submit handler
function onSubmit(event) {
  event.preventDefault()
  // Styled output
  let output = original
  
  // Get text to be converted to green
  const greenText = document.querySelector("#toGreen").value
  // Get text to be converted to yellow
  const yellowText = document.querySelector("#toYellow").value

  // Change all `greenText` to green and return
  output = changeColor(output, greenText, 'green')
  // Change all `yellowText` to yellow and return
  output = changeColor(output, yellowText, 'yellow')

  // Print styled string to screen
  document.querySelector("#styled").innerHTML = output
}

function changeColor(string, text, color) {
  return string.replace(text, `<span style="color: ${color}">${text}</span>`)
}
<form>
  <label for="fname">To green:</label>
  <input type="text" id="toGreen"><br><br>
  <label for="lname">To yellow:</label>
  <input type="text" id="toYellow"><br><br>  
  <input type="submit" value="Submit">
</form>

<h3>Original</h6>
<div id="original"> he walked to the store and then he walked to his house,</div>
<h3>After</h6>
<div id="styled"> he walked to the store and then he walked to his house,</div>

在代码段中,输入需要更改为“green”和“yellow”的单词。然后按Submit

要实际更改字符串内的单词颜色,您需要将其包装在 .然后仅更改该 CSS<span/><span/>

changeColor方法将特定单词包装在 element.innerHTML 中'<span/> and change it color, then return the styled string. Then you can put this styled string in

0赞 Sahab 11/15/2023 #3

让我们看看为什么您的方法可能有问题:

  • 您的模式可能与整个单词不匹配,因此它也会更改其他部分中的单词。

  • 您没有颜色分配方法

我们如何解决它:

  • 我们可以有一个 getWordAndColor 方法将颜色设置为单词
  • 我们可以有另一种方法将句子单词更改为指定颜色

const getWordAndColor = () => {
        let wordAndColor = {};
        wordAndColor['he'] = 'green';
        wordAndColor['walked'] = 'red';
        wordAndColor['store'] = '#4682B4';
        return wordAndColor;
    }
    const setColorToWord = (wordAndColor, sentence) => {
        for (let key in wordAndColor) {

            if (wordAndColor.hasOwnProperty(key)) {
                let value = wordAndColor[key];
                let dynamicPattern = key;
                let pattern = new RegExp("\\b" + dynamicPattern + "\\b", 'gi');
                let replacement = '<span style="color: '+value+';">'+key+'</span>';
                sentence = sentence.replace(pattern, replacement);
            }
        }

        return sentence;
    }

    let sentence = "he walked to the store and then he walked to his house,";
    let wordAndColor = getWordAndColor();
    document.getElementById('wordAndColorText').innerHTML = setColorToWord(wordAndColor, sentence);
<div id="wordAndColorText"></div>

评论

1赞 cerdessius 11/16/2023
天哪,太谢谢你了!这正是我想要的。我非常感谢你!!
0赞 Sahab 11/16/2023
@cerdessius,谢谢你,很高兴看到它为你工作。