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

Issue: unable to inject ngAnimate due to uncaught object error

Whenever I attempt to inject 'ngAnimate' into my app, I encounter issues with instantiation. Here is the code snippet in question: var app = angular.module('musicsa', [ 'ngCookies', 'ngResource', 'ngSanit ...

Utilizing Bootstrap divs for multiline display in Yii2 platform

Currently, I am utilizing a list in Bootstrap CSS which is responsive and beneficial. However, I am faced with the challenge of creating a notification list with lengthy text akin to that on Facebook. My query pertains to the technique required to make th ...

Triggering a JQuery slider event on each individual slider handle within the range

Can events be triggered based on the movement of individual slider handles? I am curious because I need to dynamically update a datepicker depending on which handle is moved. However, I'm unsure if there is a way to: Specify an event for a specifi ...

The ng-repeat function is currently disabled and not displaying any data from the JSON object

I am currently facing an issue where the ng-repeat Directive in my code is getting commented out and not displaying the results of the JSON object. I have verified that the object is being properly passed to "this.paises2" using the toSource() method, and ...

The combination of Asp.net and Bootstrap offers a powerful

I am facing an issue with using Bootstrap in my ASP.NET project. The page displays correctly on a desktop, but when I resize the page to mobile phone size, the navigation panel does not stay in dropdown position. Here is my code: <%@ Page Language="C ...

Automatically update data in Angular without the need to refresh the page

One feature of my application involves displaying a table with rows retrieved from a database. The functionality responsible for fetching this data is an AJAX call, implemented as follows: getPosts(): Observable<Posts[]> { return this.http.post ...

Simulating an API request using Vue and Jest/Vue test utils

Utilizing Vue for the frontend and Python/Django for the backend, I aim to create tests that verify the functionality of my API calls. However, I am encountering difficulties when attempting to mock out the Axios calls. I suspect there might be an issue w ...

Access the value of a variable from a window resizing event and utilize it in a different

I have a carousel that I'm working with and am trying to figure out how to announce the number of currently visible slides when the "next" button is clicked. While I can see that on resize, the correct number of slides is being logged, I am strugglin ...

A fresh checkbox was added to the page using Jquery Switchery to disable it

I'm having trouble disabling the Switchery checkbox. When I try to disable it, another Switchery checkbox appears on the page along with the one I previously defined: <div class="form-group"> <label class="col-md-2"> ...

The Vuetify data-table header array is having trouble accepting empty child associations

My Vuetify data-table relies on a localAuthority prop from a rails backend. Everything runs smoothly until an empty child association (nested attribute) is passed, specifically 'county': <script> import axios from "axios"; exp ...

Is there a way to obtain cookies on a Server-side component in the latest version of Next.js?

import axios from "axios"; const Api = axios.create({ baseURL: "http://127.0.0.1:5000", }); axios.defaults.headers.common["Authorization"] = cookie; In server-side environment, document.cookie is not accessible. Alternat ...

Implementing the @media rule using Javascript

I'm trying to use JavaScript to add an image dynamically, but I want to remove it when the viewport is 600px or wider. This is my approach so far: var img = document.createElement('img'); // (imagine here all the other fields being defined ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...

How can you prevent multiple instances of JavaScript objects from being disposed of after they have completed their task?

I'm facing an issue with the code snippet below: $(document).ready(function() { $('.container').ready(function() { var v = new Video($(this)); v.load(); }); }); I'm trying to prevent the object 'v&apos ...

How can I create a hyperlink that leads to multiple pages?

I am looking to create a hyperlink that will lead to a random webpage each time it is clicked from a selection of URLs. Can anyone suggest a suitable function to get started on this task? ...

The plugin 'vue' specified in the 'package.json' file could not be loaded successfully

There seems to be an issue with loading the 'vue' plugin declared in 'package.json': The package subpath './lib/rules/array-bracket-spacing' is not defined by the "exports" in C:\Users\<my_username>\Folder ...

Accessing data from a live database in a randomized sequence

When retrieving items from a database, there is often a common code pattern that looks like this: const [dataRcdArray, setDataRcdArray] = useState<never[]>([]); ..... snapshot.forEach((child:IteratedDataSnapshot) => { setDataRcdArray(arr ...

Encountered an issue while loading a pretrained JSON model in a JavaScript script within a locally hosted

At the moment, I am using TensorFlow in Python to train a model and saving it as model.json along with the BIN file in a folder named models. My goal is to develop a web application that can load this pre-trained model for prediction. However, I have been ...

What is the best way to manage the "checked" state of an input checkbox using React?

I'm currently developing an application that features a form with radio buttons. One of the radio button options can be toggled on/off using a checkbox, but I want to ensure that the checkbox is disabled if the corresponding radio button is not selec ...

Generating a dynamic method for uploading multiple files

Is there a way to dynamically generate multiple upload forms upon clicking a button? I currently have code that allows for uploading one file, but I would like to be able to add additional forms for each file. In other words, if I need to upload 7 files, I ...