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.
}
}
}