Using replace to change different strings?


#1

For example, in the sentence, "All cats are mammals", I'd like to use replace to change it into "All lizards are reptiles"

I know how to change one string:

{string="All cats are mammals"}
{=replace(string, "cats", "lizards")}

But I don't know how to change multiple strings.


#2

You can nest the replace() calls:

{string="All cats are mammals"}
{=replace(replace(string, "cats", "lizards"), "mammals", "reptiles")}


#3

Got it. Thanks :slight_smile:

Any possibility this might be simplified in the future?


#4

This is unlikely to be changed. Optimizing this specific use case probably wouldn't be worth the increase in the complexity of the function.


#5

Ok, no worries :grinning:


#6

I've created a "ready made" snippet for people who want to do it the easy way with formtext

This is the text you want to modify:
"{formtext: name=string; default=All cats are mammals}"

Replace "{formtext: name=string1old; default=cats}" with "{formtext: name=string1new; default=lizards}"

AND

Replace "{formtext: name=string2old; default=mammals}" with "{formtext: name=string2new; default=reptiles}"

This is the modified text:
"{=replace(replace(string, string1old, string1new), string2old, string2new)}"