Search code examples
powerappspowerapps-canvasnintex-workflow

How to do string interpolation on the content of a string variable OR How to evaluate an expression embedded in a string


I know that one can embed expressions in a string using $"{expression}", and PowerFX will evaluate the expression and insert the result in the string.

Set(Result, $"Answer is {12 + 2}");
// Result = "Answer is 14"

I would like apply that sort of string interpolation to a string variable that contains the expression syntax. For example:

Set(Template, "Answer is {12+2}");
Set(Result, $ExpressionString);
// Result is "Answer is 14"

The goal is to read a template string from a data source with placeholders, then insert the values of the fields or expressions referenced.

I am trying to replicate the Nintex Workflow "embedded variables" function from the StringBuilder action.

The syntax needed to do it myself "the hard way" is beyond me. Something like:

  • Use regex to find all instances of "(?<placeholder>{(?<expression>[^}]*)})" in the template string.
    • MatchAll() would return a table of the matches
  • Iterate the matches and create / alter a results string
    • calculate the value of <expression> [1]
    • remove <placeholder> from the template
    • insert the value of <expression> in the template

[1] This is the part I'm most lost on. In other languages, there might be an "exec(expression)" function, that everyone would agree is a terrible thing and can introduces vulnerabilities when misused.


Solution

  • There is not a viable way to do this today.

    There's no "execute" a string like Eval() - exactly for the reasons you alluded to. But even if you tried to build this yourself - you could use a regex to find the placeholders, but you still don't have a way to evaluate the expressions in the placeholders... that just begs the question of needing an Eval(). Eg, instead of Eval($"answer is {1+2}"), you still need Eval("1+2").

    FWIW, String interpolation was recently introduced in Power Fx (https://powerapps.microsoft.com/en-us/blog/power-fx-string-interpolation-index-function-and-randbetween-function/)