Skip to main content
May 24, 2024
Solved

How to replace/substitute placeholders with values in a string using either reduce or forEach?

  • May 24, 2024
  • 4 replies
  • 1 view

Hi All,

We have small requirement like need to replace/substitute the places holders in string with values.

a!localVariables(
  local!template: "Hello, {name}! Welcome to {place}.",
  local!placeholders: {
    "name": "John",
    "place": "Appian"
  },

  a!forEach(
    items: a!keys(local!placeholders),
    expression: a!localVariables(
      local!placeholder: fv!item,
      local!value: local!placeholders[local!placeholder],
      local!template: substitute(
        local!template,
        "{" & local!placeholder & "}",
        local!value
      ),
      local!template
    )
  )
)

which returns the following out put like 

List of Text String - 2 items

    • "Hello, John! Welcome to {place}."(Text)
        • "Hello, {name}! Welcome to Appian."(Text)

        Need to replaced all of them in single string with some sequential manner.

        Your expertise is helpful to solve.

        Thanks in advance.

          Best answer by stefanhelzle0001

          a!localVariables(
            local!InputString :"Hello, {name}! Welcome to {place}.",
            local!Placeholders: {
              "{name}",
              "{place}"
            },
            local!values: {
              "John",
              "Appian"
            },
            reduce(
              substitute(_,_,_),
              local!InputString,
              merge(local!Placeholders, local!values)
            )
          )

          4 replies

          konduruc733182
          May 24, 2024

          Where are you trying to use this?

          ramkumarpAuthor
          May 24, 2024

          In one of our use case we are having this requirement. like one of the interface will provide the paragraph with some place holders while generating the report interface we have to replace those place holders with actuals. So he are trying to write one expression rule with Input as placeholders string and outcome is replaced content/string like.

          Input String :"Hello, {name}! Welcome to {place}.",
          Placeholders: {
          "name": "John",
          "place": "Appian"
          },

          Output result is :"Hello, John! Welcome to Appian."

          stefanhelzle0001
          Brainy
          May 24, 2024

          a!localVariables(
            local!InputString :"Hello, {name}! Welcome to {place}.",
            local!Placeholders: {
              "{name}",
              "{place}"
            },
            local!values: {
              "John",
              "Appian"
            },
            reduce(
              substitute(_,_,_),
              local!InputString,
              merge(local!Placeholders, local!values)
            )
          )

          ramkumarpAuthor
          May 24, 2024

          Thank you Stefan