replace finds some text in a string and changes every place it appears. Wrap the search text in slashes, and it becomes a regular expression.
Syntax
replace(<STRING>, <SEARCH>, <REPLACEMENT>)
<STRING>: the text to change.<SEARCH>: the text to find. Every occurrence is replaced. Written as/…/, it’s a regular expression.<REPLACEMENT>: the new text. With a regular expression,$1and similar insert captured groups.
The function is described in replace Function (opens in a new tab) in the OpenTofu® docs.
Prerequisites
- OpenTofu installed. Installing OpenTofu (opens in a new tab) in the OpenTofu docs covers every system.
Step 1: Try It in tofu console
Open a terminal in any empty folder and start tofu console, which evaluates expressions as you type them:
tofu console
Type each expression to see the result. The last one uses a regular expression:
> replace("1 + 2 + 3", "+", "-")
"1 - 2 - 3"
> replace("Tea & Biscuits", "&", "and")
"Tea and Biscuits"
> replace("hello world", "/w.*d/", "everybody")
"hello everybody"
> exit
Clean Up
Type exit to leave the console. The example creates nothing, so there’s nothing else to remove.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Expecting only the first occurrence to change | Every occurrence is replaced. | Make the search text more specific if you need fewer changes. |
| Searching for text that starts and ends with a slash | It’s read as a regular expression. | Escape it, or search for a part without the slashes. |
FAQ
Can I chain replacements?
Yes. Put one inside another: replace(replace(s, "a", "b"), "c", "d").
Does replace change the variable?
No. It returns a new string.
Conclusion
replace(<STRING>, <SEARCH>, <REPLACEMENT>) returns the string with every match of the search text replaced.
Additional Resources
OpenTofu® is a registered trademark of LF Projects, LLC. Other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with or endorsed by the OpenTofu project.
0 comments