Encase Regex Matches from the Inner Text of an Element in HTML Tags

I have a div element with some content inside. I am trying to use regular expressions to target specific parts of the text, wrap them in span elements with a class attribute "highlight-yellow" and add a custom attribute called my-custom-attribute="hello".

Let's look at an example of what I'm working with...

Input

<div class="content"> This is a sample text $HIGH:LOW $LOW:HIGH </div>

Output

<div> This is a sample text <span class="highlight-yellow" my-custom-attribute="hello">$HIGH:LOW</span> <span class="highlight-yellow" my-custom-attribute="hello">$LOW:HIGH</span></div>

How can I go about making this replacement? Below is the code snippet that captures the matches:

   function handle()
{
    let element = document.getElementsByClassName('message')
    let text = element[0].innerText;
    let regex = /([^=])\$([A-Za-z:]{1,})/g;
    let matches = text.match(regex);

    if(matches != null)
    {
        for(let i = 0; i < matches.length; ++i)
        {
            // TODO replace the matches with spans having attributes.
        }
    }
}

Answer №1

To easily incorporate your regular expression, utilize String.prototype.replace() and wrap the desired markup around your capturing group.

I have excluded the initial capturing group as it was matching empty whitespace before, which may not be the desired outcome. Additionally, I recommend utilizing querySelectorAll to iterate through the node list for a more robust setup.

If your intention is to only target the first element that matches the selector .message, this can also be achieved.

Please note: Your output appears to strip the message class from the original <span> element - it's unclear if this is intentional or an error.

View the proof-of-concept example below:

function manipulateContent() {
  const regex = /\$([A-Za-z:]{1,})/g;
  
  document.querySelectorAll('.message').forEach(item => {
    item.innerHTML = item.innerText.replace(regex, '<span class="highlight-yellow" my-custom-attribute="hello">$1</span>');
  });
}

manipulateContent();
span.highlight-yellow {
  background-color: yellow;
}
<span class="message">This is some text $HIGH:LOW $LOW:HIGH</span>

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

The input box is not properly filled with the complete string using protractor sendKeys

[HTTP] --> POST /wd/hub/session/ffcd7072-9f96-45cb-a61d-ec53fc696b56/element/0.9513211246393813-32/value {"value":["1","0","0","0","1"],"text":"10001"} My JavaScript code snippet: this.zipcode = element(by.model('personalInfo.zipcode')); this ...

Retrieving hashtags from a text

If I had a string like this var feedback = "Yum! #yummy #delicious at #CZ" Is there an efficient way to extract all the hashtags from the string variable? I attempted using JavaScript's split() method, but it seems cumbersome as I have to repeate ...

The 'export '__platform_browser_private__' could not be located within the '@angular/platform-browser' module

I have encountered an issue while developing an angular application. Upon running ng serve, I am receiving the following error in ERROR in ./node_modules/@angular/http/src/backends/xhr_backend.js 204:40-68: "export 'platform_browser_private' w ...

The Ajax form is failing to send any headers

Whenever I submit my form, the header data doesn't seem to be coming through. Even though I've done this type of submission numerous times (figuratively speaking), there's always a chance that I might be overlooking something. Any ideas? Che ...

React components multiplying with every click, tripling or even quadrupling in number

My app enables users to create channels/chatrooms for communication. I have implemented a feature where pressing a button triggers the creation of a channel, using the function: onCreateChannel. Upon calling this function, the state of createChannel chan ...

When new AJAX content is loaded, Isotope container fails to properly target the new objects and instead overlaps the existing ones

My webpage loads all content through an AJAX call. Initially, I tried placing my isotope initialization code inside a document ready function, but it didn't work as expected: $(function(){ container = $('#content'); contain ...

Adjust ChartJS yAxes "tick marks"

I'm having trouble adjusting the scales on my yAxes and all the information I find seems to be outdated. My goal is to set my yAxes range from 0 to 100 with steps of 25. Check out this link yAxes: [ { ...

Improving the functionality of multiple range slider inputs in JavaScript codeLet me

Is it possible to have multiple range sliders on the same page? Currently, all inputs only affect the first output on the page. Check out an example here: http://codepen.io/andreruffert/pen/jEOOYN $(function() { var output = document.querySelectorAl ...

JavaScript's XMLHttpRequest

My attempt to bypass the WebGoat prompt involved using a combination of javascript code with XMLHttpRequest to send multiple requests, one using GET and the other using POST. The code snippet is as follows: <script> var req1 = new XMLHttpRequest() ...

Enhancing this testimonial slider with captivating animations

I have designed a testimonial slider with CSS3 and now I am looking to enhance it by adding some animation using Jquery. However, I am not sure how to integrate Jquery with this slider or which plugins would work best for this purpose. Can anyone provide g ...

JavaScript: Creating an array of images from a directory

I've encountered a problem that has proven to be more complex than expected - I am struggling to find resources related to my specific question. My goal is to store 36 images from a folder on my computer into an array using Javascript. Below, you will ...

Error: Docker/Next.js cannot locate module '@mui/x-date-pickers/AdapterDateFns' or its respective type definitions

When I run the command npm run build, my Next.js application builds successfully without any issues. However, when I try to build it in my Dockerfile, I encounter the following problem: #0 12.18 Type error: Cannot find module '@mui/x-date-pickers/Ada ...

When you hover over an image, its opacity will change and text will overlay

I am looking for a way to decrease the opacity and overlay text on a thumbnail image when it is hovered over. I have considered a few methods, but I am concerned that they may not be efficient or elegant. Creating a duplicated image in Photoshop with the ...

When utilizing a Service through UserManager, the User variable may become null

Utilizing Angular 7 along with the OIDC-Client library, I have constructed an AuthService that provides access to several UserManager methods. Interestingly, when I trigger the signInRedirectCallback function from the AuthService, the user object appears ...

Automated updating of Google Map markers

I am looking for a way to continuously update the marker on my Google Map to reflect my current position every 15 seconds using Jquery. Can anyone provide guidance on how to achieve this? Here is my code snippet: var x=document.getElementById("message"); ...

Issues with visuals in jQuery.animate

I have nearly finished implementing a slide down drawer using jQuery. The functionality I am working on involves expanding the drawer downwards to reveal its content when the handle labeled "show" is clicked, and then sliding the drawer back up when the ha ...

Using the @ Symbol in Javascript ES6 Module Imports

One of the folders in my node_modules directory is called @mymodule, and within it, there is another folder named 'insidefolder'. The path to this folder looks like this: node_modules/@mymodule/insidefolder When trying to import insidefolder us ...

Is AJAX causing issues with my media uploader and color picker?

Currently, I have incorporated tabbed navigation within a WordPress admin page and it is functioning properly on its own (data can be saved). However, I am now looking to implement some AJAX functionality for toggling between pages. The issue arises when t ...

The functionality of a basic each/while loop in jQuery using CoffeeScript is not producing the desired results

I've been experimenting with different methods to tackle this issue. Essentially, I need to update the content of multiple dropdowns in the same way. I wanted to use an each or a while loop to keep the code DRY, but my experience in coffeeScript is li ...

The React DOM isn't updating even after the array property state has changed

This particular issue may be a common one for most, but I have exhausted all my options and that's why I am seeking help here. Within my React application, I have a functional component named App. The App component begins as follows: function App() ...