Issue with Regex, replacing only 1 instance of string

PavelP
Mega Sage

Hello,

I created a simple Regex, to dynamically change the background color in an email template. The Color appears in 2 places in the template (this cannot be changed!). When I run the Regex - Replace function, it changes just the first occurrence.

Any idea what I'm doing wrong? What could be done for it to work as expected and change both instances?

 

Regex:

 var r2 = new RegExp(/background: .*;/);
  var RAG = 'color';
 body = body.replace(r2, "background: " + RAG + ';');

 

The String:

<table style="width:100%; border-collapse: collapse" border="1" cellspacing="0" cellpadding="0">
    <tbody>
        <tr style="padding: 5px;">
            <td style="width:100%;border: 1pt solid windowtext;background:green; padding: 5px;" colspan="2">
                <h3 style="text-align: center"><strong>TEXT</strong></h3>
            </td>
        </tr>

.....

        <tr style="height: 17.55pt;">

            <td style="border: 1pt solid windowtext;background:green; padding: 5px;" colspan="2">
                <h4 style="text-align: center;"><span class="label">TEXT</span></h4>
            </td>
        </tr>
        <tr style="height: 35.1pt; border-bottom: 1pt solid;">
 
 
 
Thanks in advance
best regards
Pavel
1 ACCEPTED SOLUTION

Hi,

yes you're right. In the end, it was fixed by using /gm

https://www.w3schools.com/jsref/jsref_regexp_m.asp

View solution in original post

3 REPLIES 3

Tony Chatfield1
Kilo Patron

Hi,if you want to replace all values use the global flag IE /yourregex/g

https://www.w3schools.com/jsref/jsref_replace.asp

Hi,

yes you're right. In the end, it was fixed by using /gm

https://www.w3schools.com/jsref/jsref_regexp_m.asp

Hitoshi Ozawa
Giga Sage
Giga Sage

Hi Pavel,

Instead of .replace(), use .replaceAll().

 body = body.replaceAll(r2, "background: " + RAG + ';');

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll