executeScript_Sandbox Javascript replace exact match

Hi @Plankton @Timo @thecoder2012 @ulrich

I use a javascript to replace but this javascript NOT replace the exact match word i need the replacement exact word.

With this javascript if i have AAAHOME it replace in BBBHOME

I need only replacement if the value is AAA replace in BBB

In this case this javascript must NOT replace nothing because there are not exact match

My macro code

{
  "Name": "ZZZ Replace_Multiple",
  "CreationDate": "2020-2-11",
  "Commands": [
    {
      "Command": "store",
      "Target": "AAAHELLOBBB",
      "Value": "MyVar"
    },
    {
      "Command": "executeScript_Sandbox",
      "Target": "var mystring = ${MyVar}; var replaced = mystring.replace(/AAA/g, \"ZZZ\").replace(/BBB/g, \"TTT\"); return replaced",
      "Value": "MyNewvar"
    },
    {
      "Command": "echo",
      "Target": "${MyNewVar}",
      "Value": ""
    }
  ]
}

Log

[status]

Playing macro ZZZ Replace_Multiple

[info]

Executing: | store | AAAHELLOBBB | MyVar |

[info]

Executing: | executeScript_Sandbox | var mystring = ${MyVar}; var replaced = mystring.replace(/AAA/g, “ZZZ”).replace(/BBB/g, “TTT”); return replaced | MyNewvar |

[info]

Executing: | echo | ${MyNewVar} | |

[echo]

ZZZHELLOTTT

[info]

Macro completed (Runtime 1.17s)

Thanks to all

Hmm, if you only have a few cases, a simple conditional can help. So (in pseudo code notation)

  • if var = “AAA” then var = “BBB”.
  • if var = “ZZZ” then var = “TTT”.

So no “replace” command required, only “if” command used.

The other option is to use replace with regular expressions e. g.

Hi thanks for reply, my problem is that I have a large amount of words to replace and change periodically I need an integrated jaascript solution.

Can you help me to edit this code to replace only exact match word please ?

I know little javascript

    {
      "Command": "store",
      "Target": "AAAHELLOBBB",
      "Value": "MyVar"
    },
    {
      "Command": "executeScript_Sandbox",
      "Target": "var mystring = ${MyVar}; var replaced = mystring.replace(/AAA/g, \"ZZZ\").replace(/BBB/g, \"TTT\"); return replaced",
      "Value": "MyNewvar"
    },

Thanks

I wish I could help more, but regular expressions are not my strength :roll_eyes:

This answer seems to do what you need, but I have not tested it: https://stackoverflow.com/questions/40075099/javascript-replace-exact-match-string

Thanks I try to edit javascript code reading the example and try to adapt the code.

Thanks