Encountering Issues with Formatting InnerHtml Text using RegEx

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>

Answer №1

The issue probably stems from your form triggering a default page repaint. To fix this, include a "type" attribute in your <button>:

<button type=button onclick="Prettyfy()">

(The presence of the form appears unnecessary.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Zod: ensure at least one field meets the necessary criteria

Currently, I am in the process of developing a form that allows users to input either their email address or phone number. While they have the option to provide both, they are required to enter both before proceeding. For this project, I am utilizing Zod a ...

Having trouble executing the typescript build task: Command 'C:Program' is not valid as an internal or external command

I'm currently working on converting typescript code to JavaScript and have been following the steps outlined in the documentation. To automate the compilation of .ts files, I set up a watch task triggered by pressing Ctrl+Shift+B. However, upon runni ...

Storing socket.io data in an array

Having trouble getting the desired array of arrays from my socket.io emitter. The structure I need is: [ [{...},{...},{...}] , [{...},{...}] , [{...}] ] But instead, I am receiving a different format. https://i.stack.imgur.com/3PY0u.jpg I require all t ...

Top method for creating a checkbox filter to toggle the display of elements depending on various data-* attributes

I am currently working on creating a checkbox filter that will display or hide elements based on multiple data attributes assigned to those elements. Despite my attempts, I have not been able to achieve the desired filtering outcome. You can view a basic ...

Is it necessary to execute 26 individual mysql queries in order to group items alphabetically in a directory listing page?

I am looking to create a directory listing page for my website that displays all of my articles grouped by the first letter of their titles. Do I have to execute 26 MySQL queries like: mysql query like "SELECT * FROM articles Where title like 'a%&ap ...

Raising the css value for each element that is impacted

I am faced with an infinite number of elements that I need to arrange next to each other. Each element has a class called "box". My goal is to separate each box by 10px increments, meaning the first element will have a left property of 0px, the second 10px ...

Upon refreshing the browser, an error pops up saying "unable to set headers after they have been sent."

Error image: app.get('/home', function (req, res, next) { usersession = req.session; if (usersession.loggedin == true) res.redirect('/home'); res.sendFile(path.join(__dirname, 'index.html')); }); ...

Once the window width exceeds $(window).width(), the mouseenter function is triggered exponentially

My side menu smoothly folds to the right or left based on the size of the browser window. However, I noticed that upon first reload, the mouseenter and mouseleave events are triggered twice for each action. While this isn't a major issue, it becomes p ...

Why is the camera access permission dialog not showing up in the WeChat app?

Why is it that when I attempt to open the following links for the first time, Chrome asks for camera permission, but when I access them through WeChat's in-app browser, the camera permission dialog does not appear? Can someone shed some light on this ...

"Failure in bundling with NodeJS using nexe and fusebox

I am attempting to convert a nodejs application into an .exe file. I initially tried using pkg, but encountered errors with half of the node-modules. Now, I am experimenting with a different method. However, when I run the following command: nexe index.js ...

Nodemailer is experiencing difficulties when used within the routes directory

Recently, I encountered an issue with my subscribe form. It functions perfectly when called from app.js where the express server is defined. However, when I move subscribe.js to the routes folder and connect both files, it fails to send emails. Upon pressi ...

I'm at a loss with this useState error, can't seem to figure

Could you please help me understand what is incorrect in this code snippet? import React, { useState } from 'react'; import UsrInput from '../component/UsrInput' import TodoItemList from '../component/TodoItemList' const ...

Turn a textfield on and off in real-time

Hey everyone, I've been working on making a textfield dynamic and I wanted to share my code with you: <input type="text" id="test1" value ="dynamic" onfocus="this.disabled=true" onblur="this.disabled=false"> <input type="text" id="test2 ...

Automatically formatting text upon entering it in Vue.js

I need assistance with auto-formatting the postal code entered by the user. The rule for the postal code is to use the format A0A 0A0 or 12345. If the user inputs a code like L9V0C7, it should automatically reformat to L9V 0C7. However, if the postal code ...

Stringified HTML code showcased

When working with Angular, I have encountered an issue where I am calling a function inside an .html file that returns a string containing a table element. My goal is to convert this string into HTML code. I attempted to use [innerHtml]: <p [innerHtml ...

How can I implement a sliding page effect using jQuery with a single navigation bar?

I came across a helpful tutorial at this link: I really admire the sliding effects on this website: Is there a way to achieve similar sliding effects like dk new media's, but with just a single navigation bar? ...

Struggling to successfully transmit my form information to my email

I've been trying to figure out how to get the information submitted through the form on my website sent to my email, but I can't seem to make it work... Here's what I have in my email.php file: <?php $EmailFrom = "<a href="/cdn-cgi/ ...

How to customize the background of radio buttons in HTML

I want the background color to stay consistent as lightgray for each <ul>. Currently, clicking the radio button causes the ul's background to change incorrectly. I am unsure of how to loop through all available ul elements using jQuery and woul ...

Ways to prioritize HTML5/CSS3 navigation menu above the content

I am attempting to position my navigation menu on top of the content. Despite using z-index and overflow = visible, the desired effect is not achieved. I want to avoid setting the position relative as it will push the content downwards. Simply put, I want ...

Button click functionality for updating in Classic ASP is functioning correctly exclusively in Internet Explorer and not in other web browsers

Currently, I am in the process of enhancing a Classic ASP application. Within this application, there is an HTML table that is populated from a SQL database. One cell within the table contains checkboxes. Upon clicking one of these checkboxes, a popup wind ...