Technology: React.js
I have been working on a custom function in JavaScript to highlight specific words within a code block. The function seems to be functioning correctly, but the highlighting isn't staying after the function is completed. Any ideas on how to make the changes stay permanently? Here is an example snippet:
CSS
<style type="text/css">
.highlight
{
color: red;
}
.example
{
background-color: lightgrey;
width: 200px;
height: 80px;
padding: 5px;
}
</style>
JavaScript
<script type="text/javascript">
function HighlightWords() {
var keywords = ["let", "const", "var"]
for (var i = 0; i < keywords.length; i++) {
var keyword = keywords[i];
var text = document.getElementById("sample").innerHTML;
var regexPattern = "(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + keyword + ")\\b";
var regex = new RegExp(regexPattern, "ig");
document.getElementById("sample").innerHTML = text.replace(regex, '<span class="highlight">' + keyword + '</span>');
}
alert(document.getElementById("sample").innerHTML);
}
</script>
HTML
<body>
<form id="form" runat="server"> <pre id="sample" class="example">
<code>
const message = "Hello World"
let count = 5
</code>
</pre>
<br />
<button onclick="HighlightWords()">Highlight Keywords</button>
</form>
</body>