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

Why does Asp.net Webform load twice every time I click on the form link?

In my asp.net webform project, I am encountering an issue where the page is running twice when clicked. The problem arises when calling two functions (Fill DropDowns) on the Page_Load Event. During debugging, it was observed that the control enters the Pa ...

css problem with scaling in firefox

My goal is to create a website that adjusts its size based on the document size. When the document size is between 0px and 1024px, I want the design to be responsive. This can easily be achieved with CSS media queries. Similarly, when the document size is ...

jQuery live function is not functioning as anticipated

I am facing issues with ajax requests and simple <input type="submit"/>. I have a practice of loading views within other views, in a modular way, using jQuery's .load(url) function to move from one view to another. The problem arises when I loa ...

Is there a way to substitute the final character in the specific regex I've selected?

I have a specific string that I need to modify from {Rotation:[45f,90f],lvl:10s} to {Rotation:[45,90],lvl:10}. Here is the code I tried: const bar = `{Rotation:[45f,90f],lvl:10s}` const regex = /(\d)\w+/g console.log(bar.replace(regex, '$&a ...

The Checkbox generated by Javascript is failing to properly close the tag

When I generate a checkbox in this manner and insert it into my table's [TD] tag: let checkbox = document.createElement('input'); checkbox.type = 'checkbox'; td.appendChild(checkbox); It yields: <tr> <td> ...

ways to utilize inline styling in react using javascript

When repurposing an array of React components, I am looking to modify the inline styles generated with them. How can I access and log the inline styles of a React component? UPDATE: see the code snippet below: const pieces = this.props.pieces.map((decl, ...

AngularJS - issue with directive functionality on dynamically inserted classes

Check out this plnkr - I've got a button that toggles the class toggled on the body element. I've also developed a directive to trigger an alert when the toggled class is applied to the body element, but for some reason it's not working. H ...

Is Nuxt's FingerprintJS Module the Ultimate Server and Client Solution?

I am currently using fingerprintJS in my NuxtJS+Firebase project VuexStore. When I call the function on the client side, I can retrieve the Visitor ID. However, I am encountering issues when trying to use it on the server side, such as in nuxtServerInit. ...

Having trouble getting DeviceOrientationControls to function properly

For the past week, I've been attempting to use my smartphone's orientation controls to manipulate my three.js scene. Although I lost the tutorial that originally guided me, I managed to find the example I saved from it. However, despite studying ...

What is the best way to make a click handler respond to any click on an "a" tag, regardless of its surrounding elements?

If I have the following HTML code: <a href="/foo">bar</a> <a href="/"> <div></div> </a> And I am looking to create a jQuery handler that will respond when ANY "a" tag is clicked: $(document).click((e) => { ...

Using .after() in AngularJS for nested ng-repeat recursive iteration

I have a straightforward layout function adjustLinks($scope) { $scope.links = [ { text: 'Menu Item 1', url: '#', },{ text: 'Menu Item 2', url: '#' ...

Do not forget to implement Array.find when working with the useSWR hook in Next.js

I have the following code: const fetcher = (url: string) => axios.get(url).then((r) => r.data); const {data} = useSWR("api/data", fetcher, {refreshInterval: 10000}) console.log(data.find(d => d.id === "123")) The API path is ...

Using jQuery to Navigate through Different Routes in React Router

Hey there, I've managed to get my React-Router set up quite well but now I'm facing a new challenge. I need to implement some JavaScript functionality. For example: When the user enters their login details and clicks 'login', I want my ...

Deploying an Express.js application: The command 'PassengerAppRoot' is invalid, possibly due to a misspelling or being defined by a module not included in the server configuration

I am looking to host an express.js app on cPanel. After successfully installing node, nvm, and npm, I managed to upload all the necessary files to the server and configure the .htaccess file. However, despite my efforts, cPanel's error logs are still ...

There was an error with the response code of 500 on the development server for react-native

An issue has been encountered on the node.js window: error: bundling failed: Error: Unable to resolve module react-native-gesture-handler from node_modules\@react-navigation\native\src\Scrollables.js: react-native-gesture-handler could ...

Can someone help me identify the issue with my JavaScript code?

Recently, I attempted to transfer data from JavaScript to HTML using Angular. Here is the code snippet: phonecatControllers.controller('start', ['$scope', function($scope){ $scope.lloadd=true; console.log('data - '+$ ...

utilizing object methods to retrieve object attributes

I am currently working on developing a new application named myApp. This application includes a property called regularNameErrors and a method called populateJSON. The populateJSON method utilizes an AJAX call to retrieve a JSON object, which is then added ...

Setting a fresh keybinding in Atom on macOS

Recently, I decided to switch over to using Atom on my Macbook and I wanted to set up a keybinding where alt-up arrow would act as page up and alt-down arrow for page down. Despite my efforts, I have not been successful in getting this to work. I'm p ...

Automatically append version number to requests to avoid browser caching with Gulp

When deploying my project, I utilize gulp to build the source files directly on the server. In order to avoid caching issues, a common practice is to add a unique number to the request URL as explained in this article: Preventing browser caching on web app ...

Create a line break in an alert using PHP

<?php function alert($msg) { echo "<script type='text/javascript'>alert('$msg');</script>"; } if(array_key_exists('btnRegisterAdmins', $_POST)) { $fname = $_POST['FirstName']; $lname=$_POST['La ...