Power Automate: replace Function

Power Automate: replace Function

by: Manuel ⏱️ ✏️ Updated: 📖 6 min read 💬 13

The "replace" function is one that shows up frequently in every programming language. The usage is simple but extremely powerful.

Usage

It follows a simple pattern.

  1. Main string
  2. Old Text
  3. New Text

Let's start with an easy one.

Example:

replace('Hello World', 'World', 'Home')

will return

'Hello Home'

The function will replace the instances of "World" with the word "Home." But what if we have multiple instances of the word.

Example:

replace('Apple#Banana#Pear', '#', ',')

will return

'Apple,Banana,Pear'

The function will always replace all instances of the word in question. For the last example, I want to give you a more usable scenario to use in your daily life.

Example:

replace('Manuel ## Gomes', '##', 'T.')

will return

'Manuel T. Gomes'

I'm giving this example on purpose because this can be quite a nice trick. You can have template strings with placeholders that you can replace with the final values. Think of examples like email templates where you have the full email in a string or a file and only want to "replace" it for the name of the person. You can have placeholders like "###1" and "###2" and then replace them for the real values and send.

Non-intuitive behaviors

The function is case-sensitive

The "replace" function matches exactly, including the case. Looking for "world" will not find "World", and you'll get your string back untouched with no error to tell you why. It's a silent miss, which makes it a horrible one to debug.

A common trick is to lowercase the string first with the "toLower" function, but be careful, because that changes the whole string:

Example:

replace(toLower('Hello World'), 'world', 'Home')

will return

'hello Home'

Notice that "Hello" is now "hello". You get the match, but you lose the original casing. If the casing matters to you, do the matching on a lowercased copy and keep the original around.

You can't type a new line directly

This one catches everybody. Writing '\n' in the expression doesn't give you a new line. It gives you two literal characters, a backslash and an "n". The function looks for that, finds nothing, and hands the string back unchanged.

To get a real new line, build the character with the "decodeUriComponent" function:

replace(variables('MyText'), decodeUriComponent('%0A'), ', ')
Windows line endings need both characters

Text coming from a Windows file, an email body, or a copy and paste from Excel usually ends its lines with a carriage return and a line feed, not just a line feed. If you replace '%0A' and still see stray characters, replace '%0D%0A' instead.

Limitations

Everything must be a string

You can only use strings. It's not possible to pass integer values directly, for example. You'll get an error like this:

Example:

replace('Manuel ## Gomes', '##', 2)

will return the following error:

Unable to process template language expressions in action 'Compose_2' inputs at line '1' and column '2853': 'The template language function 'replace' expects its third parameter 'new string' to be a string. The provided value is of type 'Integer'. Please see https://aka.ms/logicexpressions#replace for usage details.'.

The same error will show up for any other type, so keep this in mind if you have variables and use them as parameters to the function. The good news is that the fix is a small one. Wrap the value in the "string" function and the function will take it happily:

Example:

replace('Manuel ## Gomes', '##', string(2))

will return

'Manuel 2 Gomes'

No wildcards and no regular expressions

The function only matches literal text. There's no way to say "replace anything that looks like a date" or to use a pattern of any kind. If you need that, you'll have to break the string apart with the "split" function and put it back together, or do the work outside the flow in an Office Script or an Azure Function.

If you searched for this and found people talking about a "use regular expressions" checkbox, they're talking about Power Automate Desktop, which is a different beast. Cloud flows don't have it.

Troubleshooting Common Errors

The template language function 'replace' expects its first parameter 'string' to be a string. The provided value is of type 'Null'

Cause: The string you're feeding the function is empty. This happens all the time with an empty SharePoint column or a variable that was never set, because those come through as null and not as an empty string. It's a nasty one because it tends to show up halfway through a loop, after the flow has happily processed hundreds of items that did have a value.

Solution: Wrap the value in the "coalesce" function to give it a fallback. If the value is null, it becomes an empty string, and the function is happy again.

replace(coalesce(triggerOutputs()?['body/Title'], ''), '#', ',')

The template language function 'replace' expects its first parameter 'string' to be a string. The provided value is of type 'Object'

Cause: You passed the whole thing instead of one of its properties. It's an easy mistake to make when you pick a value from the dynamic content and it hands you the full body of the action.

Solution: Drill into the property you actually want. You could wrap it in the "string" function, but that gives you the whole JSON as text, which is almost never what you wanted.

replace(body('Get_item')?['Title'], '#', ',')

Recommendations

Here are some things to keep in mind.

Don't build everything in the same formula

Ensure that you have only strings and keep the formula as simple as possible. Even if you have to make some more steps with variables or composes, you'll be able to debug and see if any value is not what you're expecting.

Don't use this function inside other actions

Other actions have formula fields, but it makes it harder to debug. Do all the parsing before using it.

Don't nest it

It's possible, and you won't get an error, but it will be harder to debug also. Step by step, always.

Final Thoughts

The "replace" function is one of those tools you'll reach for constantly, and it does its job well as long as you remember its two rules. Everything has to be a string, and it matches exactly what you type, so no patterns and no forgiveness on the casing. Keep the expressions small, check for empty values before you hand them over, and it will serve you well.

Sources

Back to the Power Automate Function Reference

Photo by Utopia By Cho on Unsplash

Comments (13)

JCL | |

Hi, Can the replace function be used to replace part of every string within an array in Power automate? While reading an RSS Feed and filtering it to post a message with the selected items on a MS Teams channel, one of the string variables is at the origin RSS Feed an HTML code expression with a relative link in between. I do not have access to change the RSS feed. Is there a way to replace the all the "href='/web" in the array strings for "href='https://www.site.org/web"sot that the links could work? Thanks in advance for any help!

Manuel Gomes Author | |

Hi JCL It's possible, yes. You need to do a "Apply to each" fetch each element of the array. Then you can do the replacement: replace(item(),'href=’/web','href=\’https://www.site.org/web') Note that the quotes for the formula are ' and the ones you're using are ’. In this case, it will work because the quotes you're using are interpreted as a string, but be careful if you use ' in your strings. Cheers Manuel

JCL | |

Hi again, Thanks for the reply. Tested the replace(body('Filter_array'),'href=''/web','href=''https://www.site.org/web') [used duplicated apostrophes to overcame the ' in the middle of the expressions). I'm using the full array "body('Filter_array')",because if I choose the array item containing the HTML string to be partially replaced power automate creates an Apply to Reach fort the array item within another apply to reach for the array. I must be doing something (very basic) in the wrong way... Apply to Each to the Array filter result (previous step) by imputing onto the "Select an output from previous steps" the filtered array "body('Filter_array')" and then use a" Compose" to do the replacement with the above expression. The replacement only works if I convert the array to a string: replace(string(body('Filter_array')),'href=''/web','href=''https://www.site.org/web') However, how do I invoke the items of replaced Array in the next steps? Do I need to convert it back to an array? I can only see a "Current item" outcome without knowing what type of object it is. And that gives me an error for the next step (publishing in MS Teams Channel)... sigh...

JCL | |

PS Sorry for typos...

JCL | |

Any help? thanks in advance... I've tried everywhere for guidance already.

Manuel Gomes Author | |

Hi JCL, Don't worry. We'll get your Flow working. Cheers Manuel

JCL | |

You can find it here: powerusers.microsoft.com/t5/Building-Flows/RSS-filtered-Array-item-replace/m-p/849735#M119013 Thanks in advance!

Jacob Mulquin | |

Hi Manuel, I've created a tool that your readers may find useful when it comes to the replace function. It is a tool that generates nested replace function: https://mulquin.com/articles/power-automate-replace-generator I hope you and others find it useful!

Manuel Gomes | |

Great job Jacob! Indeed useful!

jana | |

There is bit confision in article: Limitations You can only use strings. It’s not possible to replacement of integer values, for example. You’ll get an error like this: Example: replace('Manuel ## Gomes', '##', 2) will return the following error I disagree. Correct syntax (with 2 in quotation) : replace('Manuel ## Gomes', '##', '2')

Manuel Gomes | |

Hi Jana, Indeed you're right; the correct syntax is with quotations. My comment is because when you put something in quotations (even a number), it becomes a string. So 2 is a number while '2' is a string that contains one character that is a number but could be something else. I know it's confusing, but I see this error all the time, so I wanted people to be aware and careful about it Thanks!

Leave a Comment

All comments are reviewed for spam before being displayed 5000 left
Replying to